Menu

Adding Controls Programmatically In ASP.NET

it's all about the page life cycle
Adding Controls Programmatically In ASP.NET

The beauty of working on .NET web forms is that every control that you see on the screen is an object of some kind, inheriting from the base Object. Which means that we have the liberty of working with them in all kinds of ways. We can drag them onto the designer, or position them manually (as I'm assuming every single person does), and if the need arise we can also add then programmatically to our web pages. Say for example that the fields we collect for a user table such as name, lastname, email, etc all come from a database table. In this case, if we ever needed to collect more information, we'd simply just add a record to our database. So we have to create these controls on the fly when the page loads. I'll document the process in the way that I learned it the first time I tried it out.


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

private void AddControls()
{
     TextBox firstname = new TextBox();
     TextBox lastname = new TextBox();

     // assuming we have a panel object on our page already
     panel.Controls.Add(firstname);
     panel.Controls.Add(lastname);
}


If we run that application, we'll get our desired controls to render on the page. We're getting there. Now we take care of the problems that arise from this. Since there's no point in just having unused textboxes, we will have to capture their text values and do something with them. What that is doesn't matter too much for now. However, where do we call our save function? We can't call it before we add the controls, because the controls won't exist yet as children of the Page, and we'll get a run time error. So we load our controls first, and then if the request is a postback, then we can save the data. But first some quick background on the ASP.NET Page Life Cycle.

The Page Life Cycle

The Page Life Cycle is comprised of several events that happen when an ASP.NET page is requested. Everything from rendering the controls, to loading viewstate data, to handling postback events will happen in this sequence. When adding controls dynamically you must take into account what happens when and be sure to handle the process just at the right moment to avoid headaches. The first time I attempted dynamic controls, I kept losing control data and was capturing data at the wrong times.

A few things to note. We have to render our controls every time whether postback or not, otherwise on postback they will be lost. Also we must give our controls ID's in order to retrieve the data from them later on. While ASP.NET gives each control a default name if we don't provide one, we can't use that to retrieve the controls back server side. Most importantly, the right time to add dynamic controls to our pages is during the PreInit event in the page life cycle.


protected override void OnPreInit(EventArgs e)
{
   base.OnPreInit(e);
   AddControls();
}

You can use OnPreInit for the following purposes:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.

By loading our controls here, we'll make sure that they get into the ViewState so that we can grab the data on page load and do whatever it is we need to with it.

Full Example

protected void Page_Load(object sender, EventArgs e)
{
     if (IsPostBack)
     {
         TextBox firstname = (TextBox)this.FindControl("firstname");
         Response.Write("first name: " + firstname.Text);
     }
}

private void AddControls()
{
     TextBox firstname = new TextBox();
     firstname.ID = "firstname";
     pnlDynamicControls.Controls.Add(firstname);

     TextBox lastname = new TextBox();
     lastname.ID = "lastname";
     pnlDynamicControls.Controls.Add(lastname);
}

protected override void OnPreInit(EventArgs e)
{
     base.OnPreInit(e);
     AddControls();
}

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment