GroupBox Validating event isn’t firing on ValidateChildren call

07 Jun

The Validating event code for GroupBoxes below checks if at lease 1 CheckBoxes checked in the group. It works with Form.AutoValidate enabled. But when Form.ValidateChildren() is called, this validating event isn’t firing.

' Validate if at least 1 of the CheckBoxes in the GroupBox is checked
Private Sub GroupBox_Validating(ByVal sender As System.Object, _
                                ByVal e As System.ComponentModel.CancelEventArgs) _
    Handles GroupBoxStatus.Validating, GroupBoxClass.Validating

    Dim isValid As Boolean = False
    For Each ctrl As Control In DirectCast(sender, Control).Controls
        If TypeOf ctrl Is CheckBox Then
            If DirectCast(ctrl, CheckBox).Checked Then
                isValid = True
                Exit For
            End If
        End If

    If isValid = False Then
        Me.ErrorProvider1.SetError(DirectCast(sender, Control), "Check at least one item")
        e.Cancel = True
        Me.ErrorProvider1.SetError(DirectCast(sender, Control), "")
        e.Cancel = False
    End If

End Sub

Although the documentation on MSDN said “Calling ValidateChildren is equivalent to calling ValidateChildren with a ValidationConstraints of None.”, invoking ValidateChildren(ValidationConstraints.None) actually makes it work.

Private Sub btnQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnQuery.Click

    If Me.ValidateChildren() Then
        MessageBox.Show("This message always shows no matter the GroupBoxes are valid or not.")
    End If

    If Me.ValidateChildren(ValidationConstraints.None) Then
        MessageBox.Show("This message only shows when the GroupBoxes are valid")
    End If

End Sub
Leave a comment

Posted by on June 7, 2012 in .NET, VB, Winform


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: