Windows Forms modal dialog that returns an object, not DialogResult

I was kind of stuck in this, so I was hoping that someone could help me.

I am making a Winforms application and I need to show a Modal Dialog (form.ShowDialog) that returns a value (it asks the user for some values ​​and wraps them in Object).

I just can’t understand how to do this, and not give a reference to the object or, depending on some form of public property, in order to subsequently read the data.

I just want ShowDialog to return something else, but that doesn't work. Is this some kind of “good” way to do this?

I'm sure the problem is not new, but since almost no one seems to make Winforms anymore, I cannot find any directions on the Internet.

+5
source share
4 answers

Add a static method to your form, for example:

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:

var myObject = MyDialog.ShowAndReturnObject();

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

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

+12
source

You can create a public property inside the dialog box that represents the return 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();
}
+2
source

ShowDialog , , . , , - .

0

. Ok. DialogResult, . , Ok Cancel, DialogResult. , "", . try-catch-finally using. , .

0

All Articles