Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create div tag dynamically

Tags:

c#

asp.net

I want to create a DIV dynamically and place it into another DIV when a button is clicked.

So far I've managed to create a new DIV on button_click, however I don't know how to place the new DIV object into a specific DIV tag as a child.

Here's my code which is within the button's click event.

   System.Web.UI.HtmlControls.HtmlGenericControl dynDiv = new    System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
   dynDiv.ID = "dynDivCode" + i.ToString();
   dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Gray");
   dynDiv.Style.Add(HtmlTextWriterStyle.Height, "20px");
   dynDiv.Style.Add(HtmlTextWriterStyle.Width, "300px");

   dynDiv.InnerHtml = "I was created using Code Behind";

   this.Controls.Add(dynDiv);

Any suggestions please? thanks

like image 791
Rizwan Shahid Avatar asked Mar 01 '26 22:03

Rizwan Shahid


1 Answers

Your specific existing div should be server control. For example: Panel. Then you can add as a child to the Controls collection of the panel.

like image 125
Samich Avatar answered Mar 06 '26 16:03

Samich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!