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...
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.