|
-
Feb 4th, 2008, 03:46 AM
#3
Re: [2.0] Pass data between forms?
The question of how to pass data between forms comes up a lot here. It's also an indication of bad programming practice.
There are two primary types of form: application windows and utility windows.
Application windows stay on-screen all the time; they are where the user does their work.
Utility windows are things like floating toolboxes and dialogue boxes. Your question involves dialogue boxes.
Forms should not contain application logic.
The bulk of the application should be contained in separate classes. Code in forms should serve only to facilitate what appears in the form. This is a 'good practice' rule.
A dialogue box is an object, but think of it like a function. It takes data from the user and returns it to the application.
Now, just as it's bad practice to go from function to function in some kind of long chain, it's also bad practice to pass data straight from form to form. A dialogue box should be invoked from a place in your application logic, and return to that place once the user has inputted the necessary values. Functions should do only one thing, but do it well.
Best practice:
Call the dialogue box form by using its ShowDialog method. In the dialogue form logic, set the DialogResult property to return a general value (such as OK, or Cancel, or so on) and expose the actual data input as properties. You can then access the inputted values by querying the properties once control has returned to your application logic.
Here is an example:
Code:
// Create and show a preferences dialog (for example)
// A 'using' block will automatically dispose of the object when the block ends
using (PrefsDialog pd = new PrefsDialog())
{
DialogResult result = pd.ShowDialog();
// Only save changes if the user clicked OK
if (result == DialogResult.OK)
{
// Save the preference values
MyProgramSettings.Save("ExamplePref1", pd.ExamplePref1);
MyProgramSettings.Save("ExamplePref2", pd.ExamplePref2);
}
}
You should be able to work out what to write in the dialogue class.
I realise this probably isn't the answer you wanted. However, experience has taught me that this is the best approach to dealing with forms. Granted, timeshifter's example will work, and is 'easy', but is also a bad habit to get into. Develop good habits now and you will get less burnt the first time you try coding any application of non-trivial scale.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|