C#: How do you send OK or Cancel return messages of dialogs when not using buttons?

C#

C# Problem Overview


C#: How do you send OK or Cancel return messages of dialogs when not using buttons?

How would you return the OK message in the condition of a textbox that will proceed when the user presses Enter, and will send Cancel when the user presses Ctrl+Q?

Disregard: solution- this.dialogresult = dialogresult.ok or dialogresult.cancel.

C# Solutions


Solution 1 - C#

Set the form's DialogResult:

this.DialogResult = DialogResult.OK;
this.Close();

This would cause any opener that opened this form with ShowDialog() to get the given DialogResult as the result.

Solution 2 - C#

I assume you're using Windows Forms...

A couple of ways.

For OK - set AcceptButton on the form to the OK button. For Cancel - set Cancelbutton on the form to the cancel button.

OR, you can manually set the forms DialogResult to DialogResult.OK or DialogResult.Cancel and then close the form programatically.

Solution 3 - C#

Directly, in the properties of the button itself, there is the DialogResult property that can be set to OK/Cancel/Yes/No/etc... As the others have said, this can also be set programmatically.

In the properties of the form the button is on, set the AcceptButton property to your button. This will also do things like trigger the button when you hit the enter key, and highlight the button.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael RodenbaughView Question on Stackoverflow
Solution 1 - C#configuratorView Answer on Stackoverflow
Solution 2 - C#Dave MarkleView Answer on Stackoverflow
Solution 3 - C#mmmdregView Answer on Stackoverflow