Using the Button.DialogResult property in your Custom Dialog

Windows Forms

When creating a custom dialog window, like for example a custom message box or a custom input box, you will most probably need to know which dialog button was clicked by the end user. This is very easy to accomplish in C# – all you have to do is set the DialogResult property of the Button controls on your custom dialog form.

Let’s create a very quick example.

First create your custom dialog form and add an OK button and a Cancel button to it. You can customize your dialog however you like. For this example I created a simple custom error message box which is shown below:

Now to make your dialog behave like one we need to assign the DialogResult property of the Ok and Cancel buttons. You can either set these properties from the Properties Window in Visual Studio, or you could set them through code as shown below:

btnOk.DialogResult = DialogResult.OK;
btnCancel.DialogResult = DialogResult.Cancel;

And that’s basically it. When the user clicks on the Ok button your custom dialog will return DialogResult.OK and when he clicks on the Cancel button it will return DialogResult.Cancel. Easy isn’t it? 🙂

I tested the dialog out by running the following code:

private void btnShowDialog_Click(object sender, EventArgs e)
{
    CustomDialog dialog = new CustomDialog();
    if (dialog.ShowDialog() == DialogResult.OK)
    {
        Console.WriteLine("OK clicked.");
    }
    else
    {
        Console.WriteLine("Cancel clicked.");
    }
}

All I am doing is creating an instance of my CustomDialog form and calling the ShowDialog() method. Then I am checking the DialogResult returned from my CustomDialog. It’s that simple.

I hope you enjoyed this short article. Thanks for reading.

Dave.

2 comments… add one

Leave a Comment