This tutorial will show you how to create dynamic, persistent, web controls on the fly using ASP.NET 2.0 and VB.NET

In some development situations you may not know how many controls you need ahead of time. In these cases it is easier to dynamically create web controls in a container control (such as a Panel) on your form while your application is running. To do this we do not need to be importing any special namespaces, however one implication of creating dynamic controls is that the dynamic controls you create are not preserved after postbacks so you will need some mechanism to remember the controls they’ve created dynamically. One way to do is using a simple array, and this is what we’ll use in the following example. First in our _Default class we will declare a static Button array member called btn_arr, and a static int called btn_count. btn_arr will hold a copy of the controls we create on-the-fly and btn_count will keep track of how many new controls we create.

In the Page_Load event, we will read our button array and re-create all of the dynamic controls we stored in it. In this example, we read each array item into a Button object and use the Controls.Add() method of our container control (pnlMain) to add them to that controls collection.

When we actually click on our btnSubmit button the real work happens. We instantiate a new Button type and assign it some initial values taken from the UI. It is then stored in our btn_arr and passed off to our add_button() function which adds it to the Panel control’s collection.

On the front end we have a couple of text boxes that ask for the control ID, Text, and ForeColor. We also have a submit button and a label. The front end .aspx page looks something like this:

The flow for the code behind page is as follows.

Download Source Files