Reputation: 6312
I am trying to add 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 do I set the text (innerhtml) of the control itself as it doesn't seem to have as innerHtml as an attribute doesn't exist and there is no 'value' or 'text' options shown?
Thanks
Upvotes: 3
Views: 21410
Reputation: 1885
If you change the type of "divControl" to HtmlGenericControl, you should be able to set the InnerHtml property:
HtmlGenericControl divControl = new HtmlGenericControl("div");
Upvotes: 8
Reputation: 9814
I prefer this way of adding generic html controls (by using Literal):
Controls.Add(new Literal { Text = string.Format(@"<div id='{0}'><span>some text</span></div>", lb.Items[i].Value) });
Upvotes: 0
Reputation: 32107
HtmlGenericControl divControl = new HtmlGenericControl("div");
divControl.Attributes.Add("id", "myDiv");
divControl.InnerText = "foo";
this.Controls.Add(divControl);
Upvotes: 2
Reputation: 7199
You'll do it by inserting a LiteralControl within 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>"));
Upvotes: 3
Reputation: 3333
If you're just adding text, this should do it:
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 as well.
Upvotes: 0