Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement event handlers on WinForms MessageBox buttons [closed]

I have a WinForms application where, when all fields are entered, there is a save button.

On click of the save button, a messagebox appears stating 'record saved successfully'. The messagebox has two buttons, 'yes' and 'no'.

If yes, then the record should be saved and all the fields on the form should be cleared. If no is clicked, then all the fields should be cleared on the form without the record getting saved.

How can I implement this?

like image 618
Kaushik27 Avatar asked Oct 17 '25 02:10

Kaushik27


2 Answers

You don't need an event handler; the Show method of the MessageBox class returns a DialogResult:

DialogResult result = MessageBox.Show("text", "caption", MessageBoxButtons.YesNo);
if(result == DialogResult.Yes){
   //yes...
}
else if(result == DialogResult.No){
   //no...
}
like image 64
Omar Avatar answered Oct 18 '25 15:10

Omar


There is DialogResult-enum to handle such things (from MSDN)

private void validateUserEntry5()
{
    // Checks the value of the text.
    if(serverName.Text.Length == 0)
    {
        // Initializes the variables to pass to the MessageBox.Show method.
        string message = "You did not enter a server name. Cancel this operation?";
        string caption = "No Server Name Specified";
        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
        DialogResult result;
        // Displays the MessageBox.
        result = MessageBox.Show(this, message, caption, buttons);
        if(result == DialogResult.Yes)
        {
            // Closes the parent form.
            this.Close();
        }
    }
}
like image 42
bash.d Avatar answered Oct 18 '25 15:10

bash.d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!