<%@ Page %>

Creating Controls Dynamically in ASP.NET


The use of web controls provides much easier design time as well as run time experience to the programmers. However, some times it becomes necessary to generate web controls on the fly and add them to the underlaying form. For example if you are displaying search results, at design time you will not be knowing exact number of hyperlinks and link buttons ( representing Go.. or Read more.. kind of action). For such tasks we have to create controls dynamically and add them to the web form. We also need to add event handlers to these controls. In this article we will see a simple example of doing this.

Setting up the web form

In ASP.NET the web form and all the constituents has a Controls collection. For dynamically adding the controls we have to manipulate this controls collection. You probably will think that you can simply add controls to Controls collection of web form as follows :

Dim myctrl as new Linkbutton()

However, this creates some unexpected results ! Instead of adding the control as a child of Form1 it gets added after Form1. As a result the newly added control can not participate in actions like post backs.

To get around with this problem we can do this :

  • Create a web form as usual
  • Add a controls like label, link button etc. on the form
  • This control will not take part in any action but acts as base control for adding our dynamic controls
  • Add your controls to the controls collection of this control

Sample code

Here is a sample code which illustrates how to do above mentioned tasks :

Private Sub Page_Load
(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Dim l As New LinkButton()
l.Text = "hello"
AddHandler l.Click, AddressOf show

End Sub

In above code Label1 is a label control added to the form during design time. This acts as dummy controls and we will use Controls collection of Label1 to add new controls. We then add the event handler to handle click event of the link button.

Here is the Show() event handler which simply displays a message.

Public Sub show(ByVal s As Object, ByVal e As EventArgs)
Response.Write("Dynamically Added Link Button is Clicked")
End Sub

Bipin Joshi is an independent software consultant, trainer, author, and meditation teacher. He has been programming, meditating, and teaching for 25+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 14 April 2001

Tags : ASP.NET Server Controls