Why do we want to separate the data from the GUI?
One reason would be so we can keep a LOT of information, but only display a subset of it. For example we might have a lot of personal information about an employee like their pay rate and social security number. But we don't want to display that to everyone on the network. We only show that to people with Human Resources management level access.
Another reason might be so we can use one form for gathering data, and other for displaying it.
But my personal favorite need is so I can serialize/deserialize the information. Remember that GUI controls can't be serialized. So if you have a contact form like this one
how do you plan to save the data?
Of course you know you should NOT just directly access the GUI controls in every line of your code. GUI controls should always be kept private. Other classes should only change public properties. This way you can rearrange the form, change names, do whatever you need to do under-the-hood and not break all of your references to the properties.
But this still makes the data (the properties) a part of the form. So what do we do?
We make a class for your contact.
Notice that our ContactObj has more data than this form shows. That's one of the points we made earlier; that we can have more info and only show what this user's privileges allow.
We now have an object, but how do we update our earlier form to take advantage of it?
We add an instance of the ContactObj, [...]
and update our properties to use it.
Now it is just a matter of adding a couple methods to update the gui and update the object
We create a little Tester form to call our Contact form, then save the new data as an XML file after the Contact form closes.
And voila, we have a contact form with the data separated from the GUI. Our main form (tester in this case) can give the user a new contact form to obtain new data, and then save it.
But remember it could just as easily get a List<ContactObj> from a database. This would allow you to get a lot of contacts without creating a lot of forms for no reason. You could get a ContactObj and feed it into a different form that shows all the hidden properties and so on.
If you're running VS10 I've attached the finished solution.
If not, here's the final code after all the edits.
Number of downloads: 723
This post has been edited by tlhIn`toq: 07 July 2011 - 12:40 AM