flavour404
flavour404

Reputation: 6312

how do you set the innerhtml on a generic control (div) in c# code behind?

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

Answers (5)

Blair Scott
Blair Scott

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

Marek Kwiendacz
Marek Kwiendacz

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

Praveen Prasad
Praveen Prasad

Reputation: 32107

    HtmlGenericControl divControl = new  HtmlGenericControl("div");
    divControl.Attributes.Add("id", "myDiv");
    divControl.InnerText = "foo";
    this.Controls.Add(divControl);

Upvotes: 2

Humberto
Humberto

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

MK_Dev
MK_Dev

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

Related Questions