Search:

Custom Search
_________________________________________________________________

Friday, June 27, 2008

MessageBox using YesNo Button


With the previous post you could see that MessageBox class is very powerful and contains a lot of options for the static method Show. Now we will see in more detail how to implement the functionalities of a Dialog containing a YesNo Button.

When you give the user that option, it is obvious that the behavior of the Yes Button must be different from the No so you must set this.

Let's proceed to write an example. This C# code example has basicly 2 functions: when the Dialog popus up, the user must select between the Yes or No options. If the Yes is selected, the application exits. If the No button is clicked, a Dialog will appear. So here is the code:


private void button1_Click(object sender, EventArgs e)
{

DialogResult result;
result = MessageBox.Show("Are you sure you want to exit?", "Application 1", MessageBoxButtons.YesNo);
if (result == DialogResult.No) {
MessageBox.Show("App won´t close");
}
if (result == DialogResult.Yes) {
this.Dispose();
}
}

If there are more options that the user can choose from, a switch statment could be a better option:


witch (result)
{
case DialogResult.No:
MessageBox.Show("App won´t close");
break;
case DialogResult.Yes:
this.Dispose();
break;
default:
break;
}

Result when executing:



No comments: