Search code examples
c#.netwinformsrefactoringchildwindow

How to simplify the code for settings values passed between a main and child forms


I have a class that stores settings for my app. It is instantiated when the app. runs and saved when the app. closes.

public class Settings
{
    public bool showPrivacyPageOnBlogs;
    public bool showTermsPageOnBlogs;
    public bool showDisclosurePageOnBlogs;
}

And there is a popup window that displays check boxes to set these values using public properties of the popup window.

The code to handle the popup window is like:

// Horrible code ahead
private void pagesSettingsToolStripMenuItem1_Click(object sender, EventArgs e)
{
    pagesSettingsForm.showPrivacyPageOnBlogs = settings.showPrivacyPageOnBlogs;
    pagesSettingsForm.showTermsPageOnBlogs = settings.showTermsPageOnBlogs;
    pagesSettingsForm.showDisclosurePageOnBlogs = settings.showDisclosurePageOnBlogs;
    if (pagesSettingsForm.ShowDialog() == DialogResult.OK)
    {
        settings.showPrivacyPageOnBlogs = pagesSettingsForm.showPrivacyPageOnBlogs;
        settings.showTermsPageOnBlogs = pagesSettingsForm.showTermsPageOnBlogs;
        settings.showDisclosurePageOnBlogs = pagesSettingsForm.showDisclosurePageOnBlogs;
    }
    pagesSettingsForm.Dispose();
}

In my app. there are several more parameters being handled in this way so I would like to know if there is some way to simplify this code to maybe enumerate the names of the settings and allow for future addition of additional parameters.


Solution

  • Simply have the form expose a property of type Settings with a getter and a setter. That makes the snippet you posted simple without any changes needed when you add members to Settings. The effort now moves to the form implementation. PropertyGrid is a generic object editor, whether it is usable enough in your case is hard to guess.