AcceptButton won't close form

1.7k views Asked by At

I have two forms that are very similar, but in one of them clicking the AcceptButton closes the form, and in the other it doesn't close the form. Both of them have their AcceptButton set to btnAccept.

I recently created the second one, the first one has existed for awhile and was created by someone else.

They are both opened this way:

using(var form = new SomeDialog(dependency))
{
    form.StartPosition = FormStartPosition.CenterParent;
    form.ShowDialog(this);
}

Both of them handle the accept button click along these lines.

private void btnAccept_Click(object sender, EventArgs e)
{
  _dependency.DoSomething(userInput);
}

Posting my entire designer file probably wouldn't be helpful. Is there something in particular that'd be helpful to show from it? I couldn't find a similar post on StackOverflow.

What am I missing that's causing the divergent behavior?

1

There are 1 answers

0
Hans Passant On BEST ANSWER

The AcceptButton property just selects the button that will implement the default action when you press the Enter key. Clearly visible in the UI with a heavy border around the button. But that isn't enough, you still have to implement the default action.

A simple way is to set the button's DialogResult property in the designer. Which is okay but tends to cause surprises when your event handler does something like validate the dialog content, you'd have to set the form's DialogResult property back to None when you're not happy. I personally prefer to always set the form's DialogResult explicitly in the Click event handler. That's debuggable code, let's me see why it "doesn't work".