简体   繁体   中英

AcceptButton won't close form

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?

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM