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.");
        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. runs on the Thesis Theme

How smart is your Theme? How good is your support? Check out ThesisTheme for WordPress.

The Thesis Theme is one of the best Wordpress frameworks out there, especially if you understand software development, which since you're here you probably do. Thesis allows you to design post and page templates using a drag-and-drop system which gives you access to all the relevant page elements you would normally have to manually access through code. This is why understanding development techniques definitely helps, even though you don't need to write any code to get Thesis up and running.

So go check out the incredible features at DIYThemes and start using Thesis now!

1 comment… add one
  • milad moradi

    tanks very much

Leave a Comment