开发者

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

开发者 https://www.devze.com 2023-02-15 22:05 出处:网络
I am trying to add control (div) dynamically to a web page: HtmlControl divControl = new html HtmlGenericControl(\"div\");

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 t开发者_开发知识库he 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


If you change the type of "divControl" to HtmlGenericControl, you should be able to set the InnerHtml property:

HtmlGenericControl divControl = new HtmlGenericControl("div"); 


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>"));


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


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.


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) });
0

精彩评论

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