Button Array controls

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jungle38
    New Member
    • Oct 2007
    • 2

    Button Array controls

    Hi Guys. This is my first question regarding programming in a long time.

    See below a program that creates a form with a button array. The question
    is simple. After the AddHandler MessageBox.Show is executed, how do I
    refer to the button that was pressed, in order to change its color?

    I've spent a lot of time looking for this. Just got back into programming after many years!

    Thanks to all.

    [CODE=vbnet]Public btn_array(5, 5) As Button

    Private Sub Form1_Load(ByVa l sender As System.Object, ByVal e As System.EventArg s) Handles MyBase.Load

    For i As Integer = 0 To 5
    For j As Integer = 0 To 5
    btn_array(i, j) = New Button
    Me.Controls.Add (btn_array(i, j))
    btn_array(i, j).Location = New Point(10 + i * 75, 10 + j * 30)
    btn_array(i, j).Text = "Button(" & i & "," & j & ")"
    btn_array(i, j).Name = "Button(" & i & "," & j & ")"
    AddHandler btn_array(i, j).Click, AddressOf MyControl_Click
    Next
    Next

    End Sub

    Private Sub MyControl_Click (ByVal sender As Object, ByVal e As EventArgs)
    MessageBox.Show ("You have clicked control name " + sender.name)
    End Sub

    End Class[/CODE]

    OS: Windows XP Home
    Language : Visual Basic 2005
    Last edited by Killer42; Oct 29 '07, 02:34 AM. Reason: Added CODE=vbnet tag
  • cugone
    New Member
    • Sep 2007
    • 20

    #2
    You must first cast the sender (an Object type) to a Button type (it is in object form because all classes derive from Object)

    [CODE=vbnet]
    dim testButton as Button = TryCast(sender, Button)
    MessageBox.Show ("You clicked button: " & testButton.name )
    testButton.Back Color = Color.ColorValu e
    [/CODE]
    Last edited by Killer42; Oct 29 '07, 02:35 AM. Reason: Changed CODE tag to CODE=vbnet

    Comment

    Working...