<%@ 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 and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Kriya and Meditation online course are available here.

Posted On : 14 April 2001

Tags : ASP.NET Server Controls