0

我正在构建一个表单来从用户那里获取用户名和密码,但我无法让它工作。基本上当我输入用户名和密码时,如果我点击“取消”或关闭窗口,它会提取数据,但是当我按下“确定”时它会崩溃。我确信这是一个简单的修复,但我似乎无法在 Google 上找到类似的东西(这表明有更好的方法来做到这一点......但我是 vb.net 的新手,哈哈)。

这是表单(包装在一个公共函数中,返回字典中的用户名/密码):

Public Function displayLoginForm() As Dictionary(Of String, String)

    Dim loginForm As New Form()
    Dim usernameLabel As New Label()
    Dim username As New TextBox()
    Dim passwordLabel As New Label()
    Dim password As New TextBox()
    Dim okButton As New Button()
    Dim cancelButton As New Button()

    usernameLabel.Text = "Username:"
    usernameLabel.Location = New Point(10, 10)
    usernameLabel.Width = 70
    username.Height = 20
    username.Width = 300
    username.Location = New Point(80, 10)

    passwordLabel.Text = "Password:"
    passwordLabel.Location = New Point(10, 40)
    passwordLabel.Width = 70
    password.Height = 20
    password.Width = 300
    password.Location = New Point(80, 40)

    okButton.Text = "Ok"
    okButton.Location = New Point(220, 70)

    cancelButton.Text = "Cancel"
    cancelButton.Location = New Point(okButton.Left + okButton.Width + 10, okButton.Top)

    loginForm.Text = "Login Form"
    loginForm.Height = 130
    loginForm.Width = 400
    loginForm.FormBorderStyle = FormBorderStyle.FixedDialog
    loginForm.MaximizeBox = False
    loginForm.MinimizeBox = False
    loginForm.AcceptButton = okButton
    loginForm.CancelButton = cancelButton
    loginForm.StartPosition = FormStartPosition.CenterScreen

    loginForm.Controls.Add(usernameLabel)
    loginForm.Controls.Add(username)
    loginForm.Controls.Add(passwordLabel)
    loginForm.Controls.Add(password)
    loginForm.Controls.Add(okButton)
    loginForm.Controls.Add(cancelButton)

    loginForm.ShowDialog()

    Dim Result As New Dictionary(Of String, String)
    Result.Add("username", username.Text)
    Result.Add("password", password.Text)

    Return Result

End Function
4

1 回答 1

2

我错过了这条线

okButton.DialogResult = Windows.Forms.DialogResult.OK

如果将其添加到代码中,表单将毫无问题地关闭。
老实说,我不明白为什么取消按钮有效。
它应该有类似的行

cancelButton.DialogResult = Windows.Forms.DialogResult.Cancel

编辑:取消按钮的默认DialogResult属性设置为Cancel,我认为在okButton上省略DialogResult.OK(因此它默认为Cancel)会使看到AcceptButton = okButton设置为DialogResult = Cancel的winform管理器感到困惑。

于 2012-10-11T21:30:56.993 回答