Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding DIV Tags in ASP.NET

Tags:

html

c#

css

asp.net

I am attempting to dynamically add divs on a page through ASP but nothing seems to happen.

The function I created is addMainDivs()

--.aspx.cs code behind

--breakpoint

  public partial class _Default : Page
        {
            protected void addmainDiv(int m)
            {
                System.Web.UI.HtmlControls.HtmlGenericControl newdivs = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                newdivs.Attributes.Add("class", "maindivs");

                for(int i = 0; i<= m; i++)
                {
                    maindivs.Controls.Add(newdivs);
                }

            }

--breakpoint here

  protected void Page_Load(object sender, EventArgs e)
    {
        addmainDiv(1);
    }
}

Here is the aspx code:

<div id = "maindiv">
<asp:PlaceHolder ID ="maindivs" runat="server">
</asp:PlaceHolder>
 </div>

The function does not get hit at those breakpoints and this is the default start page for my app. The header and footer are hard coded but the code aboves goes into the body under a parent dive id "maindiv"

like image 617
ghost_king Avatar asked Oct 15 '25 14:10

ghost_king


1 Answers

protected void addmainDiv(int m)
{             
    for(int i = 0; i< m; i++)
    {
      System.Web.UI.HtmlControls.HtmlGenericControl newdivs = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
      newdivs.Attributes.Add("class", "maindivs");
      maindivs.Controls.Add(newdivs);
   }

}

In my question I had the first 2 lines outside the for loop in the addMainDiv() function so it only returned 1 div even with a higher parameter. Fixing that as above worked very well.

like image 193
ghost_king Avatar answered Oct 18 '25 06:10

ghost_king



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!