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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With