Dynamic creation of asp.net div

I am trying to dynamically create a div at the click of a button.

For this, I referred to this link → http://forums.asp.net/t/1349244.aspx

and made server side code (.cs) as follows →

public static int i = 0;
    protected void Button1_Click(object sender, EventArgs e)
    {
        i++;
        HtmlGenericControl newControl = new HtmlGenericControl("div");

        newControl.ID = "NEWControl"+i;
        newControl.InnerHtml = "This is a dynamically created HTML server control.";

        PlaceHolder1.Controls.Add(newControl);
    }

This code only gave me one div every time I click a button. I wanted to have a div added.

On the client side, using javascript, also I tried →

<body>
    <form id="form1" runat="server">
    <div>

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="addDiv();" />

    </div>
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </form>
</body>
</html>
<script type="text/javascript">
    function addDiv() {
        alert("Control comming in function");
        var r = document.createElement('Div');
        r.style.height = "20px";
        r.style.width = "25px";
        r.appendChild("div");
        alert("Control going out of function");
    }
</script>

Both of them did not work.

What mistake am I making?

Is there something wrong?

+5
source share
3 answers

Use this

    public int Index
    {
       get
       {
          if(ViewState["Index"]==null)
          {
             ViewState["Index"]=0;
          }
          else
          {
             ViewState["Index"]=int.Parse(ViewState["Index"].ToString())+1;
          }

          return int.Parse(ViewState["Index"].ToString());    
       }
   }

    protected void Button1_Click(object sender, EventArgs e)
    {
        HtmlGenericControl newControl = new HtmlGenericControl("div");
        newControl.ID = "NEWControl"+Index;
        newControl.InnerHtml = "This is a dynamically created HTML server control.";

        PlaceHolder1.Controls.Add(newControl);
    }
+2
source

div, div.
, asp.net PostBack .

, PlaceHolder.

+1

Just use one parent div with some ID (predefined lets say id="dvDynamic") andrunat="server"

and then use it dvDynamic.innerHTML = "<div> /* dynamic div contents */ </div>"

Its the easiest way, as if you were using the html element in ASP.net, use dom control for a better generation. Dynamically creating a control will require processing, an interface, and many things to coordinate with that control. Since it is not predetermined by the system. you have to create it.

SO selects the DOM option. it's faster and better :)

Hope this helps :)

0
source

All Articles