使用 'AddressOf' 添加处理程序
Adding Handler using 'AddressOf'
尝试向动态创建的按钮添加事件处理程序时出现错误:
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.Itm_Click
Me.pnlItemButton1.Controls.Add(Itm)
i = i + 1
If i > Temp.Length - 1 Then
GoTo Exit1
End If
我在 AddressOf 行收到一个错误:
"Item_Click is not a member of windowsapplication1.main"
我觉得这是因为我将名称设置为 "Itm" & i
但使用 AddressOf Me.Itm(i)_Click
也会出现错误。有什么想法吗?
您必须声明 event handler Itm_Click
并且它必须是可访问的。
例如(假设您的数组 Temp
存在于某处):
Public Class Demo
Protected Sub Itm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Public Sub DemoMethod()
For i As Int32 = 1 To Temp.Length - 1
Dim Itm As New System.Windows.Forms.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.White
Itm.ForeColor = Color.Black
AddHandler Itm.Click, AddressOf Me.Itm_Click
Me.pnlItemButton1.Controls.Add(Itm)
Next
End Sub
End Class
您可以将此事件处理程序用于所有动态创建的按钮。您从 sender
参数中获得被点击的按钮:
Protected Sub Itm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim actualButton = Ctype(sender, System.Windows.Forms.Button)
Dim name = actualButton.Name
End Sub
尝试向动态创建的按钮添加事件处理程序时出现错误:
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.Itm_Click
Me.pnlItemButton1.Controls.Add(Itm)
i = i + 1
If i > Temp.Length - 1 Then
GoTo Exit1
End If
我在 AddressOf 行收到一个错误:
"Item_Click is not a member of windowsapplication1.main"
我觉得这是因为我将名称设置为 "Itm" & i
但使用 AddressOf Me.Itm(i)_Click
也会出现错误。有什么想法吗?
您必须声明 event handler Itm_Click
并且它必须是可访问的。
例如(假设您的数组 Temp
存在于某处):
Public Class Demo
Protected Sub Itm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Public Sub DemoMethod()
For i As Int32 = 1 To Temp.Length - 1
Dim Itm As New System.Windows.Forms.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.White
Itm.ForeColor = Color.Black
AddHandler Itm.Click, AddressOf Me.Itm_Click
Me.pnlItemButton1.Controls.Add(Itm)
Next
End Sub
End Class
您可以将此事件处理程序用于所有动态创建的按钮。您从 sender
参数中获得被点击的按钮:
Protected Sub Itm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim actualButton = Ctype(sender, System.Windows.Forms.Button)
Dim name = actualButton.Name
End Sub