-1

VBでフォームの検証を行っており、txtName_LostFocus関数を使用してテキストフィールドのデータを検証し、間違った入力でを使用しtxtName.Focus()ました。それは私にとってうまくいきます。しかし、問題は、ユーザーが有効なテキストを入力しない場合、私のEXITボタンも機能しないことです。この解決策を修正するための解決策はありますか?

4

1 に答える 1

2

The problems you're experiencing are a result of not reading the documentation carefully. The docs for the LostFocus event make very clear that you should not attempt to set the focus (e.g., by calling the Focus method) in the handler method for this event:

Caution

Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding. For more information, see the WM_KILLFOCUS topic in the "Keyboard Input Reference" section, and the "Message Deadlocks" section of the "About Messages and Message Queues" topic in the MSDN library at http://msdn.microsoft.com/library.

A better solution is to handle the Validating event. You'll perform your input validating inside the Validating event handler method, which is raised automatically by the .NET Framework.

If the input is valid, you do nothing. If the input is not valid, you set the Cancel property of the CancelEventArgs parameter to true, causing all of the downstream events to be suppressed.

Private Sub myTextBox_Validating(ByVal sender As Object, _
                                 ByVal e As ComponentModel.CancelEventArgs) _
                             Handles myTextBox.Validating
    If Not Valid(myTextBox.Text) Then
        ' Validation failed, so cancel the event and pre-select the text.
        e.Cancel = True
        myTextBox.Select(0, myTextBox.Text.Length)

        ' Optionally (but recommended): Set an ErrorProvider control.
        ' errorProvider.SetError(myTextBox, "Invalid input")
    End If
End Sub
于 2012-04-15T10:58:33.543 に答える