Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms Modal Dialog that returns an Object rather than DialogResult

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.

like image 264
Tigraine Avatar asked Oct 27 '08 09:10

Tigraine


1 Answers

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.

like image 189
Matt Hamilton Avatar answered Oct 23 '22 14:10

Matt Hamilton