Tuesday, July 12, 2011

Moving data between forms with properties

Back when I started writing programs in C# I had no idea how to pass information between different forms. So like so many others I started by searching the internet. I found a ton of sites that showed how to do it. A lot of example code. But little explanation about what is actually going on. I think it’s more effective to know what’s happening rather than just “to do it use this code”. There are a half dozen ways you can pass data around in winforms applications in c# but the way I prefer to pass information back and forth in C# is with properties. To create a property in C# you create a field variable and a property.

Think of it like you think of a textbox. If you have textbox1 on your form you can access the .Text property of the textbox by using textbox1.text=”this”; or string variable = textbox1.text; What you’re doing is creating a form property that you can access from other forms.
Set up a windows form application in Visual Studio. Add a second form to it. In the second form create a field variable called _name and define the Name property. This is the code that does it:
private string _name;
public MyForm()
public string Name
     get { return _name; }
     set { _name = value; }
The _name variable is private which means it is visible only to the second form. When you want to change the variable in the second form you modify _name. The Name property is public and is visible everywhere in the program. When you want to change the variable anywhere except in the second form, modify Name.

Basically what happens is whenever Name is changed Set {_name = value;} takes whatever is in Name and puts it in _name. And when Name is queried, get {return _name} takes what is in _name and puts it in Name. So if we had Form1 and Form2 and our property is in Form2. Then in Form1, to send information to Form2 we would do the following:
Form2 child = new Form2();
child.Name = "Joe";
This creates an instance of Form2 called child. Then it sets the Name property to “Joe”. Then it shows the window.
If you wanted to change the name and send the new name to the form that called it, you would change the field variable in Form2 and then get the Name property in Form1.
So in Form2 you would have:
_name = “New Name”;
And in Form1 (after the ShowDialog()) you would read the property
string newName = child.Name;

See. Clear as mud.

No comments:

Post a Comment