By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,457 Members | 1,301 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,457 IT Pros & Developers. It's quick & easy.

Button Array controls

P: 2
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.

Expand|Select|Wrap|Line Numbers
  1. Public btn_array(5, 5) As Button
  2.  
  3. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  4.  
  5.         For i As Integer = 0 To 5
  6.             For j As Integer = 0 To 5
  7.                 btn_array(i, j) = New Button
  8.                 Me.Controls.Add(btn_array(i, j))
  9.                 btn_array(i, j).Location = New Point(10 + i * 75, 10 + j * 30)
  10.                 btn_array(i, j).Text = "Button(" & i & "," & j & ")"
  11.                 btn_array(i, j).Name = "Button(" & i & "," & j & ")"
  12.                 AddHandler btn_array(i, j).Click, AddressOf MyControl_Click
  13.             Next
  14.         Next
  15.  
  16.     End Sub
  17.  
  18.     Private Sub MyControl_Click(ByVal sender As Object, ByVal e As EventArgs)
  19.         MessageBox.Show("You have clicked control name " + sender.name)
  20.     End Sub
  21.  
  22. End Class
OS: Windows XP Home
Language : Visual Basic 2005
Oct 28 '07 #1
Share this Question
Share on Google+
1 Reply


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

Expand|Select|Wrap|Line Numbers
  1. dim testButton as Button = TryCast(sender, Button)
  2. MessageBox.Show("You clicked button: " & testButton.name)
  3. testButton.BackColor = Color.ColorValue
  4.  
Oct 29 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.