日期:2014-05-20  浏览次数:20840 次

十个人有九个人不会的问题
自定义了一个控件,里面有个事件
Public   Class   uctlCustom
        Inherits   System.Windows.Forms.UserControl
  Public   Event   EventCustom(ByVal   sender   As   Object,   ByVal   e   As   EventArg)
...
End   Class

把它加到一个Panel里
    Dim   WithEvents   uctl   As   uctlCustom
      Panel.Controls.Add(uctl)
...
    Private   Sub   uctl_EventCustom(ByVal   sender   As   Object,   ByVal   e   As   EventArg)   Handles   uctl.EventCustom

  End   Sub

OK这样捕捉自定义控件的事件没问题。

但是现在要动态加一打自定义控件到Panel里
                        For   i   As   Integer   =   0   To   0   11
                                uctl   =   New   uctlCustom
                                uctl.Dock   =   Windows.Forms.DockStyle.Top
                                Panel.Controls.Add(uctl)
                        Next
现在我要怎么写才能捕捉到每一个控件的EventCustom?

------解决方案--------------------
上面写错了,是这样的了.
AddHandler Me.uctl.EventCustom, New EventCustom(AddressOf Me.uctl_EventCustom)

------解决方案--------------------
用AddHandler不就完了!!!

Sub TestEvents()
Dim Obj As New Class1
' Associate an event handler with an event.
AddHandler Obj.Ev_Event, AddressOf EventHandler
' Call the method to raise the event.
Obj.CauseSomeEvent()
' Stop handling events.
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
' This event will not be handled.
Obj.CauseSomeEvent()
End Sub

Sub EventHandler()
' Handle the event.
MsgBox( "EventHandler caught event. ")
End Sub

Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class