Add Controls Dynamically

Posted by gabriel, Sun Jul 06 18:35:00 UTC 2008

Dynamic controls are an interesting topic that keep showing up in the asp.net forums. I’ll try to explain the main points about creating and working with dynamically created controls in a few articles (this one would be too long otherwise).

First of all there are two points you need to understand:
  1. Adding the controls dynamically is easy, the tricky part is getting them to stick around.
  2. The controls are not kept between postbacks therefore you have to keep recreating them every time there is a postback.
  3. The best place to recreate the controls in the Page_Load or Page_Init events.

Creating a new control is easy, it’s just a matter of instantiate the class. Adding the control to the page is also easy you only need to add the new control to the page controls.


//create a new textbox
TextBox tb = new TextBox();
//add the new textbox to the page
Page.Form.Controls.Add(tb);

You’ve seen how easy it is to add the controls but if you don’t keep recreating them when you submit the page the dynamic controls will be gone.

First understand that this need to be recreated is not exclusive for dynamic created controls. Every time there is a postback the whole page is recreated. The difference is that all the controls that are declared in the aspx page are created automatically what gives the user the impression that the controls are always there (they are not!).

Since dynamically created controls are not hard coded anywhere (obviously) you are the one responsible for recreating them.

If you create a control in the Page_Load event you’ll notice that it works just like any control already in the aspx page:


<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        TextBox tb = new TextBox();
        Page.Form.Controls.Add(tb);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

Granted that if you could create the control like this you might declare it in the aspx page as well. Ok, so let’s improve our example and create a button that adds one and only one edit to the page. If the edit already exists the button won’t do any thing.


<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        //means that the control has been created already so you 
        //need to recreate it
        if (ViewState["tb"] != null)
        {
            createDynamicControls();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //means the control has not been created yet
        //create the control and store the viewstate
        if (ViewState["tb"] == null)
        {
            createDynamicControls();
            ViewState["tb"] = true;
        }        
    }

    //this method takes care of creating the controls
    private void createDynamicControls()
    {
        TextBox tb = new TextBox();
        Page.Form.Controls.Add(tb);
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Notice that in this version of the code I created a method responsible for creating the dynamic control. This will help to encapsulate the method creation and avoid duplicating code. Also notice that I’m using the ViewState to help maintain a variable that indicates if the control has been added yet in order to avoid duplication.

When the user clicks the button I check my ViewState variable to see if the TextBox has been created, if it hasn’t I create the TextBox, add it to the page and set the ViewState variable. Now, as long as you don’t leave the page the control and it’s state will be maintained.

We could also let the user add an undefined number of TextBoxes to the page making some small changes.


<script runat="server">

    void Page_Load(object sender, EventArgs e)
    {
        //when the user first enters the page set the count as zero
        if (!IsPostBack)
        {
            ViewState["count"] = 0;
        }
        //on every subsequent postback, check the control count
        //and recreated all the controls
        else
        {
            int controlCount = (int)ViewState["count"];
            for (int i = 0; i < controlCount; i++)
            {
                createDynamicControls();
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        createDynamicControls();
        //increment the number of controls
        ViewState["count"] = (int)ViewState["count"] + 1;        
    }

    //this method takes care of creating the controls
    private void createDynamicControls()
    {
        TextBox tb = new TextBox();
        Page.Form.Controls.Add(tb);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Add TextBox" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>
 

Now you are able to add any number of controls keeping the state of them all. On my next post I’ll keep working with dynamic created controls so stay tuned.

Related posts:

Filed Under: Tips and Tutorials | Tags: asp.net dynamic controls

Comments

  1. Ned Eaton 10.06.08 / 12PM
    k4x21rt74jjis2qg botnnoc rvexawe http://luzrrdnxhni.com xpyqy jtqzodb http://sgfwvz.com vnfhoiz fral http://iykcyf.com eqgofjd dvkgt http://jmjfogatlgtv.com

Have your say

A name is required. You may use HTML in your comments.