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.
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.
Though I haven't tried that, but I strongly believe that Automapper can handle this. I think it may make your code to be like this:
// Horrible code ahead
private void pagesSettingsToolStripMenuItem1_Click(object sender, EventArgs e)
{
Mapper.Map(settings, pagesSettingsForm);
if (pagesSettingsForm.ShowDialog() == DialogResult.OK)
Mapper.Map(pagesSettingsForm, settings);
pagesSettingsForm.Dispose();
}
P.S.: I know that you said that code is horrible, but I can't not to mention that you're disposing a form which is instantiated in some other code - which is wrong, IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With