VB 2008 Create Buttons at Runtime with Event Handlers
I am trying to create a program that reads an access database, and for each record, it creates a button on a form, with the text on the form being pulled from the database. Then, for each button, it needs an event handler that will Disable the button once it is clicked, and other functions will be performed that requires the text on the button.
I've gotten as far as getting the buttons created, but I can't figure out the event handler. Using AddHandler doesn't work because it seems I can't pass any variables (ie the button text) to the handler.
Any help is appreciated. Thanks!
Se7eN16 Thursday, May 29, 2008 6:54 PM
Hi,
AddHandler is the way to go. If you need to access the properties ofthe button that was clicked, the sender variable isyour reference to that button - all you have to do is cast it to the proper type:
Code Snippet
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim clickedButton As Button
clickedButton = DirectCast(sender, Button)
MessageBox.Show(clickedButton.Text)
End Sub
Andrej
Andrej Tozon Thursday, May 29, 2008 7:47 PM
Hi,
AddHandler is the way to go. If you need to access the properties ofthe button that was clicked, the sender variable isyour reference to that button - all you have to do is cast it to the proper type:
Code Snippet
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim clickedButton As Button
clickedButton = DirectCast(sender, Button)
MessageBox.Show(clickedButton.Text)
End Sub
Andrej
Andrej Tozon Thursday, May 29, 2008 7:47 PM
Awesome! That worked! I'm a noob, so I appreciate the help.
However, can you tell me what is the point of the DirectCast? If I leave that line out then put MsgBox(sender.Text), it also works...
Thanks!
Se7eN16 Thursday, May 29, 2008 8:11 PM
Yes, the MessageBox line was there just to show you that it's the right button.
Not using DirectCastworks becauseyou allowed some VB compiler magic to help you out. If you turn the "Option Strict" option (Project Properties| Compile page)to On, you'll get a compiler error (turning this option on is a good practice because it makes your codeless error-prone- a lot more errors can be caughtin compile time).