e.Cancel会触发,但其他代码也会在发生单击事件时触发

时间:2012-03-09 16:27:37

标签: vb.net events focus validation

表单有很多按钮。其中一个按钮包含更新TableAdapterManager的代码。许多TextBox控件之一在Validating事件处理程序中都有代码。有代码可以确保美国电话号码格式正确。

如果用户选中TextBox,则验证代码可以正常工作,如果电话号码格式不正确并且焦点位于有问题的TextBox中,则会向用户显示消息。

如果用户单击具有更新TableAdapterManager代码的按钮,则会激活验证代码,但不会将焦点保留在有问题的TextBox上,按钮Click处理程序中的代码也会触发。

我想停止触发按钮代码。

以下是TextBox的Validating事件的代码:

Private Sub TextBoxPrimaryPhone_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBoxPrimaryPhone.Validating

    ' Make sure the phone is formatted correctly.
    '--------------------------------------------
    If PhoneFormat(TextBoxPrimaryPhone.Text) = "Fix Phone Number" Then

        ' Alert the user.
        '----------------
        MessageBox.Show("Please enter a 7 or 10 digit phone number.", _
                        "Entry Error", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Error)

        e.Cancel = True
    Else

        ' Format according to the length of the phone number entered by the user.
        '------------------------------------------------------------------------
        TextBoxPrimaryPhone.Text = PhoneFormat(TextBoxPrimaryPhone.Text)
    End If
End Sub

我需要包含哪些附加编码才能将焦点保留在TextBox上?

1 个答案:

答案 0 :(得分:1)

调用e.Cancel = True后,执行此操作以设置违规文本框的焦点:

TextBoxPrimaryPhone.Focus()

在按钮点击事件处理程序中,您可以执行以下操作:

    TextBoxPrimaryPhone_Validating(sender, New System.ComponentModel.CancelEventArgs)

    If Not TextBoxPrimaryPhone.Focused Then

        'Do Work

    End If