简体   繁体   中英

What is best way to pass variables between GUI in Winforms C#?

I've WinForms program with 2 GUI's. I work with one GUI and open another GUI using

        var gui = new FormGui("SomeVar", someOthervar);
        gui.ShowDialog();

I use ShowDialog() or Show() depending on what I need to get. When I'm done I would like to pass results (sometimes it's 2 strings, sometimes it's more then that) back to the Mother GUI which called Child GUI .

What's the best way to do that? I was thinking about using global variables but not sure if that's best approach?

You can create properties on your FormGui and set those within the form. When you're done with the form, you can grab those properties from your reference to the form:

var gui = new FormGui("SomeVar", someOthervar);
gui.ShowDialog();
var result = gui.Result;

EDIT: Regarding your comment:

Say your child form has some button on it or something that the user can interact with. Or if there's a close button they click on:

private void buttonCloseClick(object sender, EventArgs e)
{
   this.Result = new ResultObject()....
}

EDIT #2 Regarding your second comment:

Yes, on your FormGui class, you need to define an object called Result :

public partial class FormGui : Form
{
   public ResultObject Result {get;set;}
}

ResultObject is just something I'm making up. The point being that you're in control of FormGui , so you can add any property you want, and then access it on the FormGui object.

You can add a property on the FormGui class that contains the results you want to use in the parent form.

Also, you can use the result of ShowDialog() to pass information back as well - although this is limited values of the DialogResult enum.

您可以在子窗口上使用ShowDialog进行调用,使用新的public属性设置结果,并且当关闭对话框时,父GUI应该可以在下一个代码行中看到结果。

The answer by BFree is enough for your task

I am suggesting easy way to add properties to all forms

Make a new class extend it with System.Windows.Form

public class Form : System.Windows.Forms.Form
{
   //add properties
}

Check your properties in your forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM