Rizwan Shahid
Rizwan Shahid

Reputation: 47

Create div tag dynamically

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

Upvotes: 3

Views: 11055

Answers (1)

Samich
Samich

Reputation: 30115

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.

Upvotes: 3

Related Questions