MessageBox With DialogResult class | C# Programing | BKNMU Juangadh

 


In C#, the `MessageBox` class is commonly used to display dialog boxes that provide information, ask questions, or prompt the user for input. The `DialogResult` enumeration is often used in conjunction with the `MessageBox` to determine which button the user clicked. Here's an example of using the `MessageBox` with the `DialogResult` class:


```csharp

using System;

using System.Windows.Forms;


namespace DialogResultExample

{

    public partial class MainForm : Form

    {

        public MainForm()

        {

            InitializeComponent();

        }


        private void showMessageButton_Click(object sender, EventArgs e)

        {

            // Show a MessageBox with Yes, No, and Cancel buttons

            DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);


            // Check the result of the user's choice

            if (result == DialogResult.Yes)

            {

                // User clicked Yes

                MessageBox.Show("Changes saved!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            else if (result == DialogResult.No)

            {

                // User clicked No

                MessageBox.Show("Changes not saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            else

            {

                // User clicked Cancel or closed the dialog

                MessageBox.Show("Operation canceled.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

        }

    }

}

```


In this example:


1. We have a `MainForm` with a button (`showMessageButton`) that, when clicked, displays a MessageBox with Yes, No, and Cancel buttons.

2. The `MessageBox.Show` method returns a `DialogResult` representing the button clicked by the user.

3. We use a `switch` or `if-else` statement to check the `DialogResult` and take appropriate actions based on the user's choice.


This is a simple example, and you can customize the `MessageBox` to suit your specific needs by choosing different buttons, icons, and other options provided by the `MessageBox` class.

Post a Comment

Thanks for comment.

Previous Post Next Post