vb.net消息框单击行为不同以输入密钥

时间:2018-05-09 06:15:59

标签: vb.net messagebox

网络大师

我有以下代码。如果我鼠标单击消息框确定按钮代码行为正确但如果我按Enter键它将焦点设置回txtusename但跳转到txtpassword。有什么想法吗?

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
    If String.IsNullOrEmpty(txtUserName.Text) Then
        Dim msgResult As DialogResult = MessageBox.Show("User Name required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        If msgResult = DialogResult.OK Then
            txtUserName.Focus()
        End If
        Return

    ElseIf String.IsNullOrEmpty(txtPassword.Text) Then
        Dim msgResult As DialogResult = MessageBox.Show("Password required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        'MsgBox("Password required", vbOKOnly, vbExclamation)
        txtUserName.Select()
        txtPassword.Select()

        Return
    End If

1 个答案:

答案 0 :(得分:1)

如果txtUserName上有值且txtPassword为空或空,则显示MessageBox。显示MessageBox后(无论用户选择了什么),您选择txtUserNametxtPassword。由于您只能选择一个TextBox,因此最终会选择txtPassword

Form首先选择txtUserName,所以光标从txtPassword跳到txtUserName。最后选择了txtPassword,因此光标现在从txtUserName跳到txtPassword

您还在.Select部分使用了ElseIf。如果您想将光标设置为TextBox,则需要使用.Focus(例如If部分)。

您需要移除txtUserName.Select()上的ElseIf并使用.Focus代替.Select txtPassword来解决您的问题:

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
    If String.IsNullOrEmpty(txtUserName.Text) Then
        MessageBox.Show("User Name required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        txtUserName.Focus()
        Return
    ElseIf String.IsNullOrEmpty(txtPassword.Text) Then
        MessageBox.Show("Password required", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        txtPassword.Focus()
        Return
    End If

    'more code for database connection.
End Sub