How do you set innerhtml to a common control (div) in c # code?

I am trying to add a control (div) dynamically to a web page:

 HtmlControl divControl = new html HtmlGenericControl("div");
 divControl.Attributes.Add("id", lb.Items[i].Value);
 divControl.Attributes.Add("innerHtml", "bob");
 divControl.Visible = true;
 this.Controls.Add(divControl);

But how can I set the text (innerhtml) of the control itself, since it does not look like innerHtml, since the attribute does not exist and there are no "value" or "text" parameters shown?

thank

+3
source share
5 answers

If you change the type of "divControl" to HtmlGenericControl, you must set the InnerHtml property:

HtmlGenericControl divControl = new HtmlGenericControl("div"); 
+8
source

You do this by inserting LiteralControl into the HtmlControl:

HtmlControl divControl = new html HtmlGenericControl("div");
divControl.Attributes.Add("id", lb.Items[i].Value);
divControl.Visible = true; // Not really necessary
this.Controls.Add(divControl);

divControl.Controls.Add(new LiteralControl("<span>Put whatever <em>HTML</em> code here.</span>"));
+3
source
    HtmlGenericControl divControl = new  HtmlGenericControl("div");
    divControl.Attributes.Add("id", "myDiv");
    divControl.InnerText = "foo";
    this.Controls.Add(divControl);
+2

, :

Literal l = new Literal();
l.Text = "bob";

HtmlControl divControl = new HtmlGenericControl("div");
divControl.Attributes.Add("id", "someId");
divControl.Visible = true;
divControl.Controls.Add(l);

this.Controls.Add(divControl);

Edit: you can embed HTML in a literal too.

0
source

I prefer this way of adding generic html controls (using Literal):

Controls.Add(new Literal { Text = string.Format(@"<div id='{0}'><span>some text</span></div>", lb.Items[i].Value) });
0
source

All Articles