You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio C# ListView复选框状态保存与加载问题求助

How to Save and Load ListView Checkbox States in C#

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:02:25