我正在尝试在表单加载事件上生成许多按钮。为此,我使用按钮阵列。我希望每个按钮都有一个click事件处理程序。我几乎到处搜索,但似乎无法找到明确的解决方案。任何帮助将不胜感激。
Private Sub Home_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim tableLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
tableLayoutPanel.ColumnCount = 5
tableLayoutPanel.RowCount = 1
Dim BtnArray(5) As Button
For i As Integer = 0 To BtnArray.Length-1
tableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20))
tableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100))
tableLayoutPanel.Controls.Add(BtnArray(i), i, 0)
Next
GroupBox1.Controls.Add(tableLayoutPanel)
End Sub
答案 0 :(得分:0)
检查以下代码,它将解决您的问题
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles
MyBase.Load
Dim tableLayoutPanel = New System.Windows.Forms.TableLayoutPanel()
tableLayoutPanel.ColumnCount = 5
tableLayoutPanel.RowCount = 1
Dim BtnArray(5) As Button
For i As Integer = 0 To BtnArray.Length - 1
tableLayoutPanel.ColumnStyles.Add(New
System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20))
tableLayoutPanel.RowStyles.Add(New
System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100))
BtnArray(i) = New Button
BtnArray(i).Name = "Button" + i.ToString
AddHandler BtnArray(i).Click, AddressOf Button_Click
tableLayoutPanel.Controls.Add(BtnArray(i), i, 0)
Next
GroupBox1.Controls.Add(tableLayoutPanel)
End Sub
'Event which is call when button is click
Private Sub Button_Click(sender As System.Object, e As System.EventArgs)
MsgBox(sender.name)
End Sub