C# Windows Forms中checkedListBox选中项无法保存到应用设置如何解决?
问题根因
- 加载逻辑缺失:你仅将配置中存储的选中项集合读取到了
collectionOfTags变量,没有将集合内容同步到各个CheckedListBox控件的选中状态,是加载环节出问题的核心原因。 - 初始空值未处理:首次运行时
Properties.Settings.Default.DICOMTagSettings默认值为null,直接调用Add方法会触发空引用异常,导致保存失败。 - 保存逻辑有缺陷:每次保存直接往配置集合追加选中项,未清空历史记录,多次操作后会产生大量重复数据,也会干扰后续加载的匹配逻辑。
修复步骤
1. 确认设置项配置
打开项目属性的「设置」页,确认DICOMTagSettings的类型为System.Collections.Specialized.StringCollection,作用域设置为「用户」。
2. 修正代码
public partial class Form2 : Form { readonly Form1 form1; StringCollection collectionOfTags = new StringCollection(); public Form2(Form1 owner) { form1 = owner; InitializeComponent(); InitializeSecondForm(); } private void InitializeSecondForm() { this.Height = Properties.Settings.Default.SecondFormHeight; this.Width = Properties.Settings.Default.SecondFormWidth; this.Location = Properties.Settings.Default.SecondFormLocation; // 处理初始空值 if (Properties.Settings.Default.DICOMTagSettings == null) { Properties.Settings.Default.DICOMTagSettings = new StringCollection(); } collectionOfTags = Properties.Settings.Default.DICOMTagSettings; // 新增加载选中项的逻辑 SetCheckedListBoxSelectedItems(checkedListBox1); SetCheckedListBoxSelectedItems(checkedListBox2); SetCheckedListBoxSelectedItems(checkedListBox3); this.FormClosing += SecondFormClosingEventHandler; this.StartPosition = FormStartPosition.Manual; } // 复用的设置选中项方法 private void SetCheckedListBoxSelectedItems(CheckedListBox listBox) { for (int i = 0; i < listBox.Items.Count; i++) { if (collectionOfTags.Contains(listBox.Items[i].ToString())) { listBox.SetItemChecked(i, true); } } } private void SecondFormClosingEventHandler(object sender, FormClosingEventArgs e) { Properties.Settings.Default.SecondFormHeight = this.Height; Properties.Settings.Default.SecondFormWidth = this.Width; Properties.Settings.Default.SecondFormLocation = this.Location; Properties.Settings.Default.DICOMTagSettings = this.collectionOfTags; Properties.Settings.Default.Save(); } private void button1_Click(object sender, EventArgs e) { // 先清空旧的选中记录 collectionOfTags.Clear(); // 新增所有当前选中的项 foreach (string s in checkedListBox1.CheckedItems) collectionOfTags.Add(s); foreach (string s in checkedListBox2.CheckedItems) collectionOfTags.Add(s); foreach (string s in checkedListBox3.CheckedItems) collectionOfTags.Add(s); this.Close(); } }
3. 验证逻辑
修改后运行程序,选中对应项保存后关闭窗体,再次打开窗体即可看到之前的选中状态已经被正确保留。
内容的提问来源于stack exchange,提问作者Sanktos
相关产品推荐
相关产品推荐

