MadBoy
MadBoy

Reputation: 11104

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?

Upvotes: 0

Views: 938

Answers (4)

Javed Akram
Javed Akram

Reputation: 15354

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

Upvotes: 0

BFree
BFree

Reputation: 103750

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.

Upvotes: 4

Mor Shemesh
Mor Shemesh

Reputation: 2887

You can call with ShowDialog, on the child window, use a new public property to set the result, and when you close the dialog the parent GUI should be able to see the result in the next code line.

Upvotes: 0

davisoa
davisoa

Reputation: 5439

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.

Upvotes: 1

Related Questions