按钮在代码中创建按钮后处理

时间:2015-10-14 08:59:58

标签: vb.net events button handles

我之前在代码中创建了按钮,如下所示:

Dim Itm As New Button
Itm.Name = "Itm" & i
Itm.Height = 62
Itm.Width = 159
Itm.Text = Temp(i, 0).ToUpper
Itm.Left = (F * 165)
Itm.Visible = True
Itm.BackColor = Colour
Itm.ForeColor = Color.Black
Me.pnlItemButton1.Controls.Add(Itm)

当我运行表单时,会创建按钮,但我现在需要在单击新按钮时创建一个Event Sub。我试过这个:

    Private Sub Itm1_click(ByVal sender As System.Object, 
                 ByVal e As System.EventArgs) Handles Itm1.click

End Sub

但是得到'handle子句需要WithEvent'的错误

那我怎么能这样做呢 ?

此外,按钮的数量 - Itm(i)是可变的,那么如何创建一个将Itm1解释为Itm99的句柄?

2 个答案:

答案 0 :(得分:1)

当您定义一个动态添加的按钮时,它在运行时不存在,因此您无法设置这样的事件处理程序,您可以执行以下操作:

Dim Itm As New Button
Itm.Name = "Itm" & i
Itm.Height = 62
Itm.Width = 159
Itm.Text = Temp(i, 0).ToUpper
Itm.Left = (F * 165)
Itm.Visible = True
Itm.BackColor = Colour
Itm.ForeColor = Color.Black
AddHandler Itm.Click, AddressOf Me.Itm1_Click
Me.pnlItemButton1.Controls.Add(Itm)

然后设置受保护的事件处理程序:

Protected Sub Itm1_click(ByVal sender As System.Object, ByVal e As System.EventArgs)    
End Sub

答案 1 :(得分:1)

如果您遇到第一个错误,请查看this。它可能会帮助你。

要为您创建的每个按钮创建一个事件,请单击此处:

AddHandler Itm.Click, AddressOf Me.Itm1_Click

然后您不需要Sub中的Handles Itm1.click

Private Sub Itm1_click(ByVal sender As System.Object,ByVal e As System.EventArgs)   
       'Do stuff
End Sub