views:

2276

answers:

2

Hi. 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.

+6  A: 

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.

Matt Hamilton
Dammit :) That's almost exactly what I had (except I called my method ShowDialog -- and why not?).
Roger Lipscombe
Oh, and if you indent the code block, it'll be syntax coloured for you...
Roger Lipscombe
Hmm - I didn't call mine ShowDialog 'coz I was worried about trying to have a static method with the same name as an instance method, overloaded only by return type. I don't think that's possible.
Matt Hamilton
Hmm? Both code blocks are indented and are syntax-highlighting just fine for me.
Matt Hamilton
Why does the method need to be static?
Vulcan Eager
It doesn't, but a static method means you don't need to instantiate the form and then show it.
Matt Hamilton
A: 

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.

Kieron