2015-11-06 36 views
-1

當試圖將事件處理程序添加到動態創建的按鈕,我得到一個錯誤:處理器使用添加「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也出現錯誤。有什麼想法嗎?

+0

在哪裏聲明瞭事件處理程序「Itm_Click」?顯示更多上下文。 –

+0

對不起,我是編碼新手!我不認爲我已經宣佈了它?我應該如何申報? –

回答

1

您必須聲明event handlerItm_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