如何处理动态生成控件的事件? [英] How to handle events for dynamically generated controls?
本文介绍了如何处理动态生成控件的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在表单加载事件上生成多个按钮.为此,我使用了一个按钮数组.我希望每个按钮都有一个单击事件处理程序.我几乎到处搜索,但似乎找不到明确的解决方案.任何帮助将不胜感激.
I am trying to generate a number of buttons on form load event. For this i am using a button array. I want each of those buttons to have a click event handler. I've searched almost everywhere but can't seem to find a clear solution. Any help will be appreciated.
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
推荐答案
检查下面的代码,它会解决你的问题
Check below code,It will solve your problem
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
这篇关于如何处理动态生成控件的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文