We help IT Professionals succeed at work.

How to keep the focus back to form when clicking on OK button?

ipjyo
ipjyo asked
on
I have a windows form with multiple controls and OK and Cancel buttons. In the Click event handler of OK button, it checks to see if there are errors on the form. I need the form to stay open if there are errors. But the code below is not working. If there are errors, it is closing the form and returning to the caller. And I have the below two lines to invoke and show the form.

PtForm paymentForm = new PtForm();
ptForm.ShowDialog();


Thanks for any help.
private void btnOk_Click(object sender, EventArgs e)
        {
            this.ValidateChildren(ValidationConstraints.Visible);
            string ErrorString = GetValidationErrors();
            MessageBox.Show(ErrorString, "Errors");

            if (!string.IsNullOrEmpty(ErrorString))
            {
                return;
            }

	//Processing

	}

Open in new window

Comment
Watch Question

The code above can't close a form. It's just returning.

I suspect you set the accept button on the form to be that button.

There are many ways to approach most tasks. You could clear that setting on the form's properties and then explicitly unload the form in the button handler. You could also do your validations in one of the form's closing events and either allow or cancel the unload.

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
        }
Be careful with the above code though. You don't want to prevent the user from canceling, which that does as it's written.

Author

Commented:
Thanks for the response. Actually I verified that the form's accept button is set to none.



Well the code you posted can't possibly close the form. Make a new button, put the same code in it and you'll see that using that button doesn't close the form. Something else is responsible for closing the form, but it's not the ok handler, unless there's more code than you posted.
nishant joshiTechnology Development Consultant
Commented:
private void btnOk_Click(object sender, EventArgs e)
        {
            ((Button)sender).Focus();
            this.ValidateChildren(ValidationConstraints.Visible);
            string ErrorString = GetValidationErrors();
            MessageBox.Show(ErrorString, "Errors");

            if (!string.IsNullOrEmpty(ErrorString))
            {
                return;
            }

      //Processing

      }
Is the button's DialogResult property set to "OK" in the designer?

Author

Commented:
yeah..DialogResult was set to OK in the designer and that was the culprit.

Thank you very much.