开发者

Strings versus controls in ASP.NET WebForms

why can images not be appended to a div in asp?

divHtml.append(img);

why do I have to use div.controls.add(img);?

and why cant I add a string to controls.add say like this

div.controls.add(img + String.Format("{0}", reader.GetString(0));

? Orginally "In the beginning"

I had this code:

    cn.Open();
    using (OdbcCommand cmd = new OdbcCommand("SELECT Wallpostings FROM WallPosting WHERE UserID=" + theUserId + " ORDER BY idWallPosting DESC", cn))

    using (OdbcDataReader reader = cmd.ExecuteReader())
    {
        var divHtml = new System.Text.StringBuilder();
        while (reader.Read())
        {
            divHtml.Append("<div id=test>");
            divHtml.Append(String.Format("{0}", reader.GetString(0)));
            divHtml.Append("</div>");
        }


        test1.InnerHtml = divHtml.ToString();

    }
}

}

Which gave me this out put (notice the css is applied and all spacing etc is nice and neat:

Strings versus controls in ASP.NET WebForms

Then I did this code:

            while (reader.Read())
            {
                System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                //div.ID = "test";
                div.Style["float"] = "left";
                Image img = new Image();
                img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
                img.AlternateText = "Test image";
                div.Controls.Add(img);
                test1.Controls.Add(div);

                System.Web.UI.HtmlControls.HtmlGenericControl div1 = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                //div1.ID = "test";
                div1.InnerText = String.Format("{0}", reader.GetString(0));

                div1.Style["float"] = "left";
                test1.Controls.Add(div1);

                System.Web.UI.HtmlControls.HtmlGenericControl div2 = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                //div2.ID = "test";
                div2.Style["clear"] = "both";
                test1.Controls.Add(div2);
            }
        }
    }
}

}

And this was my result which is ok but if you notice carefully there is no css between each comment the divs are outside the realm of my css I tryed applying the commented out lines to see if it would work but its just abit funky tbh. Specialy when you look at it in firebug:

Strings versus controls in ASP.NET WebForms

This is what happens if I try parse the control using the method mentioned below:

    cn.Open();
    using (OdbcCommand cmd = new OdbcCommand("SELECT Wallpostings FROM WallPosting WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
    {
        using (OdbcDataReader reader = cmd.ExecuteReader())
        {
            test1.Controls.Clear();

            while (reader.Read())
            {
                System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");

                div.ID = "test";
                div.Style["float"] = "left";
                Image img = new Image();
                img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
                img.AlternateText = "Test image";

                div.Controls.Add(img);
                div.Controls.Add(ParseControl(String.Format("{0}", reader.GetString(0))); 

                test1.Controls.Add(div);

Strings versus controls in ASP.NET WebForms

Edit:

        using (OdbcDataReader reader = cmd.ExecuteReader())
        {
            test1.Controls.Clear();

            while (reader.Read())
            {
        System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
        div.Attributes["class"] = "test";
        div.Style["float"] = "left";

        div.ID = "test";
        //div.Style["float"] = "left";
        Image img = new Image();
        img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
        img.AlternateText = "Test image";

        div.Controls.Add(img);
        div.Controls.Add(ParseControl(String.Format("{0}", reader.GetString(0)))); 

        test1.Controls.Add(div);

Shadow managed to get this to work and I used the parse from the other comment aswell.

But problem remains now with test1 div not expanding with test divs:

Strings versus controls in ASP.NET WebForms

        <asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px" 
            onclick="Button1_Click" />
        </p>
    <p>
    </p>
        <div id="test1" runat="server" />
//could be this line
    </asp:Content>

Or it could be

test1.Controls.Add(div); 

in my code thats not being picked u开发者_Go百科p or in the correct brackets maybe? css:

div#test1 
{

}
div .test
{
  width:90%; 
  z-index:1; 
  padding:27.5px; 
  border-top: thin solid #736F6E;
  border-bottom: thin solid #736F6E;
  color:#ffffff;
  margin:0 auto;
  white-space: pre;
  white-space: pre-wrap;
  white-space: pre-line;
  word-wrap: break-word;
}


img is of type System.Web.UI.Control, which is the type accepted by Controls.Add. In particular, System.Web.UI.Control is not the same as System.String.

Since C# is a strongly-typed language, a method accepting System.Web.UI.Control (like Add on System.Web.UI.ControlCollection) cannot accept a System.String as a parameter.

Similarly, assuming divHtml is a System.StringBuilder, there is no Append method on System.StringBuilder taking type System.Web.UI.Control, so attempting to pass img to the existing Append method will fail.

(You may also be having trouble getting your code to compile since you are not using the correct names for your methods and properties; it is Controls not controls, Add not add, and Append not append.)


If you really want this, you can always create an extension method for this:

public static class ControlExtensions
{
    public static void Add(this WebControl control, string html)
    {
        control.Controls.Add(new Literal
        {
            Text = html, Mode = LiteralMode.PassThrough
        });
    }
}

Now you can do this:

div.Controls.Add(String.Format("{0}", reader.GetString(0)));


You want to add image plus literal text coming from database.

The proper way is indeed adding controls - Image control like you already have and for the text use Literal server control:

div.Controls.Add(img);
div.Controls.Add(new LiteralControl(reader.GetString(0)));

Edit: if you insist on getting the HTML string of the image control for your own reasons, it's possible using such code:

StringBuilder html = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(html))
{
    using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter))
    {
        image.RenderControl(textWriter);
    }
}

This will render the image into html variable, then you can assign the string value to the Text of some other control like you originally did. For example:

myLabel.Text = html.ToString();

Edit II: to apply CSS to the controls you're adding, first change the CSS itself from this: div#test to this instead: div .test

Now add this single line to your code:

System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.Attributes["class"] = "test";
div.Style["float"] = "left";
...

This will apply class to each top level div and this can be used to apply the proper CSS.


Because controls aren't just strings. They are objects that become strings of html when they actually render. Do some reading on control and page lifecycle in asp.net webforms.


you can add strings to a control, you will have to use ParseControl() this will convert strings to control, or as controls

div.controls.add(ParseControl(String.Format("{0}", reader.GetString(0))); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜