Understanding Dynamic Server Controls in ASP.NET

You would face scenarios in a web application where you cannot determine the number of server controls that need to be added to a web page. It will be decided only when the program is run.

In such cases, it is not possible to add a pre-determined number of controls to the web page during design time. So, what is the way out of this situation?

You have to create those server controls dynamically in the web application and then attached it to the web page. The number of controls that have to be placed will be decided on some other factor or it might come from the database.

However you will decide that type of controls that need to be used. Upon deciding this you will have to add a placeholder in the web page during design time. When the program is run, you can add controls to this place holder dynamically.

For example to add a label and textbox control to the web page, you might be using code that is similar to,

Dim AuthorName As New Label
Dim AuthorValue As New TextBox
AuthorName.Text = “some_name_from_some_variable”
AuthorValue.Text = “some_value_from_some_variable”
PlaceHolder1.Controls.Add(AuthorName) PlaceHolder1.Controls.Add(AuthorValue)

You can also attach events to the dynamically created controls as per your need.