Passing variables to Handler

guyzer1954

New member
Joined
Jan 10, 2006
Messages
4
Programming Experience
5-10
I've created an array of buttons in code . I used Add Handler for a sub.
Now I'm having a problem with which button was clicked. How can I pass
which button was clicked to the Button_Clicked Sub?
 
The button that was clicked will be passed in as the "Sender" parameter.... as long as each button has a unique name, Sender.Name will tell you which button was clicked. You might have to first cast it (or rather DirectCast it) before accessing the name property though.

-tg
 
You can also use object identity in an event handler, e.g.
VB.NET:
If sender Is Me.Button1 Then
Note that you don't have to cast the sender to make the comparison, but you do then have to cast it if you want to access its members other than those inherited from the Object class, e.g.
VB.NET:
If sender Is Me.Button1 Then
    Dim clickedButton As Button = DirectCast(sender, Button)

    MessageBox.Show(clickedButton.Text)
Note though that you have already established that the clicked button IS Button1, so you can just use that rather than casting the sender, e.g.
VB.NET:
If sender Is Me.Button1 Then
    MessageBox.Show(Me.Button1.Text)
How all this relates to your situation depends on your situation.
 
I just reread your original post and I've realised that your best bet may be to use the sender to get the index of the Button in your array:
VB.NET:
Select Case Array.IndexOf(myButtonArray, sender)
    Case 0
        'The first button was pressed.
    Case 1
        'The second button was pressed.
 
Back
Top