C# - Simple Validation - DialogResult
I have the following code for a button click on a form:
private 开发者_如何转开发void btnOK_Click(object sender, EventArgs e)
{
if (this.txtProjectName.Text == "")
{
MessageBox.Show("No project name entered", "No Project Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
btnOK.DialogResult = DialogResult.None;
}
else
{
this.btnOK.DialogResult = DialogResult.OK;
return;
}
}
If there is something in the text box, the form will only close on the second click. Is there a way to close the form instantly, and pass a DialogResult.OK to it's caller?
Thanks
Instead of setting the this.btnOK.DialogResult
, use this:
this.DialogResult = DialogResult.OK;
This will set the DialogResult
of the Form. The form will close, and DialogResult will have its correct value.
精彩评论