Handling events from dynamically created buttons (VB.NET)

This is a conversion to VB.NET from the message I posted a while back under the C# MessageBase.

Handling events from dynamically created buttons in VB.NET 1.0/1.1:

    In VB.NET, you use a command called AddHandler to define what code to run when the button is clicked. (Internally this involves things called 'delegates', but for VB.NET talk about delegates tends to confuse the issue, so going to steer away from the pure theory of things and just show you how to get things working. After you get things working, then you can look at all the theory.)
    Another common confusion is that listed in the properties for a button, there is a 'Click' event defined. DON'T USE IT. Not that you can't get it to work, but there's a lot better event to use, called 'Command' which works just like 'Click', but also allows sending additional information in the CommandArgument property. Without it, it's all but impossible to determine which button triggered the event.
    The Command event only exists for  the (you guessed it) Button, LinkButton, and ImageButton objects. This event is called Command. It fires the same as the Click event, but allows you to pass additional data via the Button.CommandArgument property. (The normal Click event does not support sending this additional data, thus why you should use the Command event instead of the Click event, unless you just need to see if a button was clicked and do not need any additional data about the click.)
    All you really need to do is create a sub that requires two objects sent to it when invoked. The first is the 'sender' object, which identifies which object is calling it (The button itself) and another object called 'CommandEventArgs'. So create a method such as:

Public Sub ButtonHandler(ByVal sender As Object, ByVal e As WebControls.CommandEventArgs)
    ' Do something...
End Sub

Now, the next thing to do is add the handler for the button to the button.command event. Say we have a button called newButton. We attach the ButtonHandler method to the Command event of newButton with the following code:

AddHandler newButton.Command, AddressOf ButtonHandler

Then, with any additional data you need to send to the ButtonHandler method, you add it to the newButton.CommandArgument property and it will be sent as part of the CommandEventArgs object that is passed via the delegate. CommandArgument only accepts a string value, so any numerical data to be sent needs to be converted to a string first. In the code example at the end of this article, I am sending both the X and Y position of the table separated by a colon. Since it's a single string, formatting of that string is up to you.

To try the following example, simply create a new web form, then drag an empty Table from underneath Web Forms in the toolbox to the new form (Leave it named the default name of Table1). Next, drag a label to the same webform, and set its name (ID under properties) to lblInfo.

Here's the example code, enjoy:

Public Class WebForm1
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
     Private Sub InitializeComponent()

    End Sub
    Protected WithEvents Table1 As System.Web.UI.WebControls.Table
    Protected WithEvents lblInfo As System.Web.UI.WebControls.Label

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Build a 10x10 table of dynamically created buttons

        Dim X, Y As Integer

        For X = 1 To 10

            Dim TR As New TableRow

            For Y = 1 To 10

                Dim TC As New TableCell

                ' Create new button and set properties
                Dim newButton As New Button
                newButton.Text = X & ":" & Y
                newButton.CommandArgument = X & ":" & Y

                ' Connect Command event to the ButtonHandler sub
                AddHandler newButton.Command, AddressOf ButtonHandler

                ' Add new button to cell

                ' Add cell to table row


            ' Add Row to table


    End Sub

    Public Sub ButtonHandler(ByVal sender As Object, ByVal e As WebControls.CommandEventArgs)

        ' Display passed X:Y info
        lblInfo.Text = e.CommandArgument

    End Sub

End Class

12/1/2005 2:16:25 AM
1/24/2006 10:31:09 AM
11/13/2006 11:58:41 AM
12/2/2006 4:26:59 AM
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: http://www.law.cornell.edu/uscode/17/107.shtml . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.