我的程序中有100多个复选框,我希望以编程方式保存这些复选框的状态,而无需在visual studio中手动创建设置属性。复选框绑定到包括nummericUpDownBox的用户控件。
我是这样保存的:
private void button2_Click(object sender, EventArgs e)
{
Settings.Default.Reset();
foreach (Control c in panel1.Controls)
{
Settings.Default.Properties.Remove(c.Name);
Settings.Default.Properties.Remove(c.Name + "value");
if ((c is checkNum) && Settings.Default.Properties[c.Name] == null)
{
SettingsProperty property = new SettingsProperty(c.Name);
property.DefaultValue = false;
property.IsReadOnly = false;
property.PropertyType = typeof(bool);
property.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
property.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
Settings.Default.Properties.Add(property);
Settings.Default[c.Name] = ((checkNum)c).Checked;
SettingsProperty property2 = new SettingsProperty(c.Name + "value");
property2.DefaultValue = 2;
property2.IsReadOnly = false;
property2.PropertyType = typeof(int);
property2.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
property2.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
Settings.Default.Properties.Add(property2);
Settings.Default[c.Name + "value"] = Convert.ToInt32(((checkNum)c).Value);
}
}
Settings.Default.Save();
}
现在,它已保存,如果我再次更改设置,我可以恢复设置。
但是如果我关闭应用程序,它就不工作了。当应用程序重新启动后关闭时,它不会保存新设置。
那么,我如何永久保存设置?这样我可以在重启应用程序后加载它。我该怎么办?
这是我加载设置的方式:
private void button4_Click(object sender, EventArgs e)
{
foreach (Control c in panel1.Controls)
{
if ((c is checkNum) && Settings.Default.Properties[c.Name] != null)
{
((checkNum)c).Checked = (bool)Settings.Default[c.Name];
((checkNum)c).Value = (int)Settings.Default[c.Name + "value"];
}
}
}