当前位置: 动力学知识库 > 问答 > 编程问答 >

vb.net - Dialog remains open on accept-button click

问题描述:

I'm building a form to get a username and password from a user and I can't get it to work. Basically when I enter in the username and password, if I hit "Cancel" or close the window it pulls the data, but when I press "Ok" it crashes. I'm sure this is a simple fix but I can't seem to find something similar on Google (which suggests there is a better way to do it... but I'm new to vb.net, haha).

Here is the form (wrapped in a public function returning the username/password in a dictionary):

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

网友答案:

I'm missing this line

okButton.DialogResult = Windows.Forms.DialogResult.OK

if you add it to your code, the form will close without problems.
To be honest I don't understand why the Cancel button works.
It should have a similar line

cancelButton.DialogResult = Windows.Forms.DialogResult.Cancel

EDIT: The cancel button has its default DialogResult property set to Cancel, I presume that leaving out the DialogResult.OK on the okButton (so it defaults to Cancel) confuses the winform manager that see an AcceptButton=okButton set with DialogResult=Cancel.

分享给朋友:
您可能感兴趣的文章:
随机阅读: