views:

176

answers:

4

How the variables can be transferred between the Winforms? Example customer id

Thanks

+1  A: 

If CustomerID is public:

frmTwo.CustomerId = frmOne.CustomerId

Jim Anderson
thanks this information is very much usefull and i am using it.
Ksmps
+2  A: 

To add to Jim's answer, you can pass variables through public properties or via the forms constructor. So

Form2 frm = new Form2(customerId);

or like Jim provided. There are many ways to getting the value, I prefer constructor if the second form is dependent on it.

Jab
+2  A: 

You must declare a public property in the form you wish to pass to. Then, after instantiating your new form, it's a simple assignment:

C#: MyOtherInstantiatedForm.CustomerID = CurrentCustomerID;

Do you need to pass around CustomerID to several forms? How about other customer information? If you provide more information we can probably give you a better solution.

Robert Venables
you don't declare variables public in OO paradigm, you use properties for that (the encapsulation principle)
zappan
+5  A: 

The most important thing to note here is that a Form is nothing more than a C# class. If you think about a Form in these terms, the answer will probably jump out, by itself.

Essentially, there are two options that you have. The first is to expose a property on the Form, for which you wish to pass data to. This is a decent method if your form does not rely on the data being passed, in order to function.

CoolForm myForm = new CoolForm();

myForm.MyProp = "Hello World";
myForm.ShowDialog();

The second option is to pass data through the constructor. I prefer this approach when the form relies on the data, in order to function. I also tend to mark the parameter-less constructor as private to ensure that the form is properly instantiated.

CoolForm myForm = new CoolForm("Hello World");

myForm.ShowDialog();

Hope that helps...

senfo
Another approach I have seen used in the past is to place data in a hidden control on a form and then have another form access it through the properties of the control. Not very elegant, but I have certainly seen it done a number of times.
Jim Anderson
Jim: Using a hidden label on a form as a public variable is worse than inelegant, its unforgivably amateurish. If your employees are using that hack to share state between forms, move them into management where they can't do any more damage to your codebase.
Juliet
I have to agree with Princess that I would strongly recommend that you not rely on hidden controls on the form. Except, I wouldn't recommend they be moved to management. I'd be afraid that they would turn into a micromanager and force these ridiculous techniques on the team.
senfo