Visual Studio C# ListView复选框状态保存与加载问题求助
No problem at all—let's adjust your existing code to preserve the checkbox checked status when saving and loading your ListView items. The key missing piece is that you weren't storing the Checked property value alongside your subitem text.
Modified Save Method
We'll update the save logic to append each item's checked state to the end of its delimited string. Here's the revised code:
private void saveListViewItems(string path, ListView lv) { var delimeteredListviewData = new List<string>(); foreach (ListViewItem lvi in lv.Items) { string delimeteredItems = string.Empty; // Add all subitem text foreach (ListViewItem.ListViewSubItem lvsi in lvi.SubItems) { delimeteredItems += lvsi.Text + "#"; } // Append the checked state at the end delimeteredItems += lvi.Checked.ToString(); delimeteredListviewData.Add(delimeteredItems); } System.IO.File.WriteAllLines(path, delimeteredListviewData.ToArray()); }
Modified Load Method
Now when loading, we'll split each line, extract the checked state from the last element, then create the ListViewItem and set its Checked property accordingly:
private void loadListViewItems(string path, ListView lv) { lv.Items.Clear(); // Clear existing items first to avoid duplicates foreach (string line in System.IO.File.ReadAllLines(path)) { string[] parts = line.Split(new char[] { '#' }, StringSplitOptions.None); if (parts.Length < 1) continue; // Skip invalid lines // The last part is the checked state; everything before are subitems string[] subItemTexts = parts.Take(parts.Length - 1).ToArray(); bool isChecked = bool.Parse(parts.Last()); ListViewItem item = new ListViewItem(subItemTexts); item.Checked = isChecked; lv.Items.Add(item); } }
Quick Note
If there's a chance that your subitem text might contain the # delimiter, you should switch to a more unique separator (like |^| or another string that won't appear in your actual data) to prevent splitting errors.
内容的提问来源于stack exchange,提问作者Mehdi Sadighian

