Generating ASP.NET controls at runtime

With the popularity of Web 2.0 and dynamic content, it has become more common to generate web controls at runtime. How do we dynamically generate a web control in ASP.NET world that would respond to user events? It seems trivial at first. However, we need to be aware of couple important subtleties. If a web control will have to respond to user events (button responds to click events), then the control would need to be defined in the Page_Initmethod. This is important in order to be able to hook the control to the event handler. In our example we will use a Button control. Let’s consider a situation where we would need to define 4 buttons that would print some text on the web page when clicked.

using System;
using System.Web.UI.WebControls;
namespace SVSS
{
    public partial class DynamicButton : System.Web.UI.Page
    {
        Button btn;
        protected void Page_Init(object sender, EventArgs e)
        {
            for (int i = 0; i < 4; i++)
            {
                btn = new Button();
                btn.Text = "Button number: " + i;
            }
        }
    }
}

We have generated 4 buttons, each one having a unique display name. The control ID is not required since it will be automatically generated. If we run the code we will not see any buttons displayed on the page. We need to add each button to the Form’s control collection.

using System;
using System.Web.UI.WebControls;
namespace SVSS
{
    public partial class DynamicButton : System.Web.UI.Page
    {
        Button btn;
        protected void Page_Init(object sender, EventArgs e)
        {
            for (int i = 0; i < 4; i++)
            {
                btn = new Button();
                btn.Text = "Button number: " + i;
                form1.Controls.Add(btn);
            }
        }
    }
}

After we have added buttons to the Form’s collection they will be displayed on the page.

We can test the buttons by clicking them. Nothing happens. They are missing an event handler. Let’s go ahead and add it.

using System;
using System.Web.UI.WebControls;
namespace SVSS
{
    public partial class DynamicButton : System.Web.UI.Page
    {
        Button btn;
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            for (int i = 0; i < 4; i++)
            {
                btn = new Button();
                btn.Text = "Button number: " + i;
                form1.Controls.Add(btn);
            }
        }

        protected void Button_Click(object sender, EventArgs e)
        {
            btn = sender as Button;
            Response.Write("You clicked: " + btn.Text);
        }
    }
}

The buttons are displaying on the page and we have an event handler defined. It is suppose to write “You clicked: Button number 1” when button 1 is clicked or any other corresponding button number if any other button is clicked. At this point, the clicking still does not produce the effect we are looking for. It is missing a very important piece. The last and final piece of the puzzle is a hook between the button controls and the event handler.

using System;
using System.Web.UI.WebControls;
namespace SVSS
{
    public partial class DynamicButton : System.Web.UI.Page
    {
        Button btn;
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            for (int i = 0; i < 4; i++)
            {
                btn = new Button();
                btn.Text = "Button number: " + i;
                form1.Controls.Add(btn);
                btn.Click += new EventHandler(Button_Click);
            }
        }

        protected void Button_Click(object sender, EventArgs e)
        {
            btn = sender as Button;
            Response.Write("You clicked: " + btn.Text);
        }
    }
}

Running the code will display the page with 4 buttons with unique names.

When we click a button the text will get displayed.

Conclusion
Generating web controls at runtime is a common requirement in web development. The key is to define them the Page_Init method and hook them up to an event handler.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.