How do I get a sub to handle the click of all a panel's child controls RRS feed

  • Question

  • My application create controls in run time, how do I get a sub to handle all of the controls in the panel it is created being clicked?


    that doesn't look vary clear, is there something like
    Handles Panel1.Controls.Click
    Friday, April 13, 2007 7:23 PM


  • Use the AddHandler keyword instead of Handles.  For example:

    Public Class Form1
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each ctl As Control In Panel1.Controls
          AddHandler ctl.Click, AddressOf PanelCtlClick
      End Sub
      Private Sub PanelCtlClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim ctl As Control = TryCast(sender, Control)
        If ctl Is Nothing Then Exit Sub ' Shouldn't happen...
        Debug.Print("Click from {0}", ctl.Name)
        '--- Do something special if it was a button
        If TypeOf ctl Is Button Then
          Debug.Print("It was a button")
        End If
      End Sub
    End Class

    Friday, April 13, 2007 8:48 PM