我想从我手动编写的配置文件中提取表单(已检查或未检查)上的复选框状态,而键指定控件名称和标记值指定是否检查:
<configuration>
<appSettings file="configuration file sample">
<add key="CheckBox1" value="true"/>
<add key="CheckBox2" value="false"/>
</appSettings>
</configuration>
使用默认的设置文件可以像这样加载:
CheckBox1.Checked = Properties.Settings.Default.CheckBox1State;
并保存如下设置:
Properties.Settings.Default.CheckBox1State = CheckBox1.Checked;
但是,如果我不使用设置文件,如何加载和保存我自己的配置文件?
答案 0 :(得分:1)
将以下方法添加到您的类中,并在CheckedChanged
事件中使用控件名称和控件状态调用此方法(已选中/未选中)。
Updating the Configuration file
private void UpdateConfiguration(string controlName, bool checkboxState)
{
//Open Configuration file for modification
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//Get the string representation(True/False) of the checkbox state
string controlState = checkboxState ? Boolean.TrueString : Boolean.FalseString;
//Set value for control (ex:CheckBox1) under AppSettings section of configuration file
configuration.AppSettings.Settings[controlName].Value = controlState;
//Save only the modified section
configuration.Save(ConfigurationSaveMode.Modified);
//Referesh the configuration file
ConfigurationManager.RefreshSection("appSettings");
}
Calling UpdateConfiguration method
UpdateConfiguration("CheckBox1", CheckBox1.Checked);