get information about dynamically created array of buttons

danijel.drmic

Member
Joined
Jul 2, 2009
Messages
10
Programming Experience
5-10
For example, when I click on the btn(5) I would like the textbox1 says: "5"
Thx
VB.NET:
Public Class Form1
    Dim btn(7) As Button

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For i = 1 To 7
            btn(i) = New System.Windows.Forms.Button
            btn(i).Location = New Point(i * 35, 35)
            btn(i).Width = 32
            btn(i).Height = 32
            btn(i).Text = i
            AddHandler btn(i).Click, AddressOf Button1_Click
            Me.Controls.Add(btn(i))
        Next
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = Button1.Text
    End Sub
End Class
 
VB.NET:
TextBox1.Text = CType(sender, Button).Text
Why do you declare an array of 8 elements and only use 7 of them? 0 is the first array index. You don't need that array at all in this code, but you probably have some reason for it.
 
Since you have an Addhandler statement you don't need a Handles clause in the sub routine, and to get the calling button's text:
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        TextBox1.Text = DirectCast(sender, Button).Text
End Sub
When you have an array of controls using the same sub you have to refer to them as sender(this is the one working currently) for any of the event subs you give it. And you use DirectCast cause you know it's a button. :cool:
 
Back
Top