Question

I'm kinda stuck with this one so I hoped someone could help me.

I am doing a Winforms application and I need to show a Modal Dialog (form.ShowDialog) that returns a value (prompts the User some values and wraps them in a Object).

I just can't see how to do this rather than give a reference into the object or depending on some form of public Property to read the data afterwards.

I'd just like to have ShowDialog return something different, but that doesn't work. Is thare some "good" way to do this?

I'm sure the problem isn't new, but since almost nobody seems to do Winforms any more I can't find any guidance on the web.

Was it helpful?

Solution

Add a static method to your form, like this:

public class MyDialog : Form
{
    // todo: think of a better method name :)
    public static MyObject ShowAndReturnObject() 
    {
        var dlg = new MyDialog();
        if (new dlg.ShowDialog() == DialogResult.OK) 
        {
            var obj = // construct an instance of MyObject from dlg
            return obj;
        }
        else
        {
           return null; 
        }
    }
}

Now you can call this from your program thusly:

var myObject = MyDialog.ShowAndReturnObject();

... and if they cancel the dialog, myObject will be null.

Now, having said all that, I do believe that adding a property to your form's class which you then read from after calling ShowDialog() is the better approach.

OTHER TIPS

You can create a public property inside the Dialog that represents the returning value:

/* Caller Code */   
var dlg = new MyDialog();
if(dlg.ShowDialog() == DialogResult.OK)
  MessageBox.Show(dlg.MyResult);

/* Dialog Code */
public string MyResult { get { return textBox1.Text; } }

private void btnOk_Click(object sender, EventArgs e)
{
  DialogResult = System.Windows.Forms.DialogResult.OK;
  this.Close();
}

Or you could create a new ShowDialog method inside your form class that does basically what Matt Hamilton's does. Maybe even an extension method if it's something you do to lots of forms in your problem.

The public property in the dialog form makes sense. However, do not close the dialog in the Ok button click event handler. When you assign the DialogResult property the dialog form will be hidden. Then in the calling form you can determine if Ok or Cancel was clicked by examining the DialogResult. Then you can access the public property if the Ok button was clicked and then dispose the dialog form. This should be done using a try-catch-finally block in the calling form or through a using statement. You must dispose of the modal dialog in order to prevent a memory leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top