The following code snippet says it all, but in short I dynamically create a bunch of buttons. When I click a button, I want the handler to know which one was pressed. In fact, I'd like to be able to pass any argument into the handler.
Private Sub SetUpRowsOfButtons()For Row As Short = 0 To 2
For Column As Short = 0 To 5
Dim NewButton As New System.Windows.Forms.Button()
NewButton.Width = 20
NewButton.Height = 20
NewButton.Top = 20 + 40 * Row
NewButton.Left = 20 + 40 * Column
Me.Controls.Add(NewButton)
AddHandler NewButton.Click, AddressOf ButtonResponder
' wish I could've passd in Row and Column---or
' even some other parameter if I wanted to!
Next
Next
End Sub Private Sub ButtonResponder(ByVal sender As Object, ByVal e As System.EventArgs
MessageBox.Show("Which button was pushed " & vbCrLf & "Row is and Column is ")
End Sub
See Regardless of which button I press, it's the same. (The ButtonResponder (handler) can get access to the button text, but that's not useful.) Halp!
Jim

need handler for array of buttons
Fluxtah
unfortunately you cant since the button click only uses a plain eventhandler.
however doing the code you have right now you can cast the sender into a button and gain all the button properties etc...
Private Sub ButtonResponder(ByVal sender As Object, ByVal e As System.EventArgs)
Dim theButton as Button = CType(sender, Button)
if theButton is nothing = false then
MessageBox.Show(theButton.Name & " was pressed")
end if
End Sub
be sure you DO create a unique name for that button you are creating programmatically
LeeroyB
Thank you, jjardine! Okay, so here's my new code:
Private Sub SetUpRowsOfButtons()For Row As Short = 0 To 2
For Column As Short = 0 To 5
Dim NewButton As New System.Windows.Forms.Button()
NewButton.Width = 20
NewButton.Height = 20
NewButton.Top = 20 + 40 * Row
NewButton.Left = 20 + 40 * Column
Me.Controls.Add(NewButton)
Dim ButtonRowAndCol As New Point(Row, Column)
NewButton.Tag = ButtonRowAndCol
AddHandler NewButton.Click, AddressOf ButtonResponder
Next
Next
End Sub Private Sub ButtonResponder(ByVal sender As Object, ByVal e As System.EventArgs)
Dim TempButton As New System.Windows.Forms.Button
If (Object.ReferenceEquals(sender.GetType(), TempButton.GetType())) Then
Dim ButtonRowAndCol As New Point
ButtonRowAndCol = sender.Tag
Dim Row As Short = ButtonRowAndCol.X()
Dim Col As Short = ButtonRowAndCol.Y()
MessageBox.Show("Row is " & Row.ToString() & " and Col is " & Col.ToString())
End If
End Sub
DavidThi808
One thing you could do is stick the information in the Tag property of the button. You could create a custom object like a point and stick your column and row in there and stuff it in the tag. Then when you are in the even handler you could cast that tag back to your object and access your values.