Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Simple Validation - DialogResult

Tags:

c#

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

like image 620
nf313743 Avatar asked Feb 15 '26 11:02

nf313743


1 Answers

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.

like image 132
GvS Avatar answered Feb 17 '26 23:02

GvS