Search code examples
c#.netformsshowdialog

Custom ShowDialog with more information than DialogResult


I need some more information than the traditional OK or Cancel states you get by ShowDialog, that is, some strings from the text boxes on my custom dialog form.

I wonder what the logic is. I would want to call it as such:

CustomDialog d = new CustomDialog();
DoStuffWith(d.ShowDialog().CustomString);

Of course, there has to be a custom class for the return result. Let's define it like this:

class CustomDialogResult
{
    public string CustomString { get; private set; }

    public CustomDialogResult(string customString)
    {
        this.CustomString = customString;
    }
}

Then we'd need to newverride the ShowDialog method in our CustomDialog : Form. I'm guessing we could start with some parented display of the form. Also, add an event handler to the OK button, which would set a result.

public CustomDialogResult CustomDialogResult { get; private set; }

private void buttonOK_Click(object sender, EventArgs e)
{
    this.Result = new CustomDialogResult(this.TextBoxCustom.Text);
    this.Close();
}

public CustomDialogResult ShowCustomDialog()
{
    this.Show(Form.ActiveForm);
}

As you can see, the problem resides in waiting for the OK button to be clicked, then to return this.Result. I could use Thread.Sleep(0) or a ManualResetEvent, but that would block the input on the dialog form. How would I go about this one? I know I could use uglier syntax, but if ShowDialog does it nicely, there has to be a way we can. :)


Solution

  • Consider the OpenFileDialog.

    It uses the standard OK result and simply exposes the extra information through properties and methods.

    To do this yourself you just need to set your Ok Button's DialogResult to DialogResult.OK and then your calling form will interrogate your extra information through a property or method.

    So the calling code looks like this

      CustomDialog d = new CustomDialog();
    
      if(d.ShowDialog() == DialogResult.OK)
      { 
          CustomDialogResult foo = d.CustomDialogResult;
          DoStuff(foo.CustomString); 
      }