In a previous article, "Dynamically load controls
into a DataGrid", I discussed a method of dynamically creating and inserting
controls into a datagrid which did not require configuration at design time.
This method allowed the run-time selection of appropriate server controls based
on the data content on a cell by cell basis. Additionally, a method for allowing
a complete screen update (as opposed to a single line update) of the underlying
data was presented.
In this article I will present two different methods for handling events
raised by dynamically inserted controls. The first method uses a combination of
Control.Attribute.add. The second method uses the
Addhandler statement to assign a delegate function to an event.
Client Side event handling
Client side event handling has the advantage
of not requiring a server round trip to handle the event. This is especially
function into the head area of the ASPX page. This example runs a function every
time a specific check box changes value.
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
alert("Are you sure?")
ItemDataBounddelegate for the datagrid, I have used
Attributes.Addfunction to associate the
Dim myCB As New CheckBox
If Not IsPostBack Then
If dgTable(dg1).Rows(e.Item.DataSetIndex)(1).tolower = "t" Then
myCB.Checked = True
myCB.Checked = False
This method is ideal for simple validation where a server round trip is not
desired. But in some cases we might need to perform more complex work...
Server Side event handling
Server Side event handling allows us to
perform complex instructions at the expense of a server round trip. This example
performs a simple
, although database lookup might be
more typical. First we need to create a subroutine with the appropriate
Private Sub MakeUpper(ByVal sender As Object, ByVal e As System.EventArgs)
CType(sender, TextBox).Text = CType(sender, TextBox).Text.ToUpper
delegate for the datagrid, I
have used the
method to assign the event handling
subroutine to the control event.
If dgTable(dg1).Rows(e.Item.DataSetIndex)(2) = "uppertextbox" Then
Dim myTB As New TextBox
If Not IsPostBack Then
myTB.Text = dgTable(dg1).Rows(e.Item.DataSetIndex)(1)
myTB.AutoPostBack = True
AddHandler myTB.TextChanged, AddressOf MakeUpper
Note that I have set
AutoPostBack = True. This will create a
postback when focus is lost. I noticed intellisense does not display the newly
created control after typing "AddHandler" (my VS version, anyway). The code will
still compile correctly.
Two methods of event handling have been presented: Client Side event handling
is appropriate for local processing which does not require server resources, and
Server Side event handling which may be more complex or require additional
resources. Good luck and Happy Coding!!