我正在构建一个表单来获取用户的用户名和密码,但我无法让它工作。基本上当我输入用户名和密码时,如果我点击“取消”或关闭窗口它会拉取数据,但是当我按“确定”时它会崩溃。我确信这是一个简单的解决办法,但我似乎无法在谷歌上找到类似的东西(这表明有更好的方法可以做到这一点......但我是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
答案 0 :(得分:2)
我错过了这一行
okButton.DialogResult = Windows.Forms.DialogResult.OK
如果您将其添加到您的代码中,表单将会毫无问题地关闭 说实话,我不明白为什么取消按钮有效 它应该有一个类似的行
cancelButton.DialogResult = Windows.Forms.DialogResult.Cancel
编辑:取消按钮将其默认的DialogResult属性设置为取消,我假设在okButton上省略DialogResult.OK(因此它默认为取消)会混淆winform管理器,该管理器看到使用DialogResult设置的AcceptButton = okButton =取消。