使用VB 2008 Express。
当单击按钮时,将代码附加到按钮上很容易,因为它们是表单上的静态按钮;只需双击表单设计器上的按钮,然后将代码添加到事件中。
我有一系列在控件数组中生成的按钮,因此它们是在类中生成的,并且在表单中直到运行时才有按钮。
所以新手问题可能只是一个简单的答案......如果在运行时将它们实例化为类之前,如何为不存在的按钮输入click事件的代码?
答案 0 :(得分:1)
我认为,对于常规按钮,你会采用这种方式。
您想对每个按钮采取什么行动?如果每个按钮的操作不同,您能举例说明它的样子吗?
编辑:未来的原始代码
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim button As Button()
ReDim button(2)
Dim button1 As New Button
button1.Top = 0
button1.Height = 100
button1.Text = "hello"
Dim button2 As New Button
button2.Top = 200
button2.Height = 100
button2.Text = "world"
button(0) = button1
button(1) = button2
For i As Integer = 0 To 1
'** This is where all the buttons are tied, to a common handler
AddHandler button(i).Click, AddressOf doSomething
Next
Me.Controls.AddRange(button)
End Sub
Protected Sub doSomething(ByVal sender As Object, ByVal e As EventArgs)
Dim thisButton As Button
thisButton = sender
thisButton.BackColor = Color.DarkBlue
thisButton.Text = "clicked"
End Sub