event handler for multiple controls vb.net
AM trying trap specific events for some controls on a form. i tried this, but its not fireing the events
For Each ctrl As Control In pnlGeneral.Controls
If TypeOf ctrl Is CheckBox Then
AddHandler (DirectCast(ctrl, CheckBox).CheckedChanged), AddressOf Control_Changed
ElseIf TypeOf ctrl Is TextBox Then
AddHandler (ctrl.TextChanged), AddressOf Control_Changed
ElseIf TypeOf ctrl Is NumericUpDown Then
AddHandler (DirectCast(ctrl, NumericUpDown).ValueChanged), AddressOf Control_Changed
End If
Next
Can anyone help me with the fix?
EDIT
I found out that am placing the control in multiple controls, on the form is a panel, inside the panel is different groupbox, these group boxes 开发者_C百科have the controls am trying to trap their events
So as Lars said it does appear to work.
edited in place to account for controls in containers
Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
Dim ctrl As Control = Me.GetNextControl(Me, True)
Do Until ctrl Is Nothing
If TypeOf ctrl Is CheckBox Then
AddHandler (DirectCast(ctrl, CheckBox).CheckedChanged), AddressOf Control_Changed
ElseIf TypeOf ctrl Is TextBox Then
AddHandler (ctrl.TextChanged), AddressOf Control_Changed
ElseIf TypeOf ctrl Is NumericUpDown Then
AddHandler (DirectCast(ctrl, NumericUpDown).ValueChanged), AddressOf Control_Changed
End If
ctrl = Me.GetNextControl(ctrl, True)
Loop
End Sub
Private Sub Control_Changed(sender As System.Object, e As System.EventArgs)
Debug.WriteLine(sender.ToString)
End Sub
Private Sub Form_Activate(Byval sender As Object,Byval e as System.EventArgs) Handles Form.Activate
Dim Ctrl as System.Windows.Forms.Control
For Each Ctrl in Me.Controls
If Typeof Ctrl Is System.Windows.Forms.TextBox then
AddHandler Ctrl.GotFocus, AddressOf TextFocus
AddHandler Ctrl.LostFocus, AddressOf TextUnfocus
Next
End Sub
Private Sub TextFocus(ByVal sender As Object, ByVal e As System.EventArgs)
CType(sender,System.Windows.Forms.TextBox).BackColor = Color.Blue
End Sub
Private Sub TextUnfocus(ByVal sender As Object, ByVal e As System.EventArgs)
CType(sender, System.Windows.Forms.TextBox).BackColor = Color.White
End Sub
精彩评论