C# 添加新项目时,如何在listview中保留选定项目?

C# 添加新项目时,如何在listview中保留选定项目?,c#,winforms,listview,items,C#,Winforms,Listview,Items,我正在尝试制作一个应用程序,它允许我检查ListView中的项目,并且所有这些都可以正常工作,但是如果我在检查项目的同时向ListView添加更多的项目。因为ListView被重新加载,所以它会取消选中它们。有没有办法绕过这个问题?所以即使我添加了新项目,我的所有项目都会保持检查状态?这是我当前的代码 TextReader reader = new StringReader(richTextBox1.Text); string[] strItems

我正在尝试制作一个应用程序,它允许我检查ListView中的项目,并且所有这些都可以正常工作,但是如果我在检查项目的同时向ListView添加更多的项目。因为ListView被重新加载,所以它会取消选中它们。有没有办法绕过这个问题?所以即使我添加了新项目,我的所有项目都会保持检查状态?这是我当前的代码

            TextReader reader = new StringReader(richTextBox1.Text);
            string[] strItems = null;
            foreach (ListViewItem items in listView1.Items)
            {
                items.Remove();
            }
            while (reader.Peek() != -1)
            {
                ListViewItem item = new ListViewItem();
                strItems = reader.ReadLine().Split("-".ToCharArray());
                item.Text = strItems[0].ToString();
                item.SubItems.Add(strItems[1].ToString());
                item.SubItems.Add(strItems[2].ToString());
                item.SubItems.Add(strItems[3].ToString());
                item.SubItems.Add(strItems[4].ToString());
                listView1.Items.Add(item);
            }

您可以这样做(并通过找到更好的标记/存在逻辑来改进它):


唯一的问题是,如果您试图删除不在新读取字符串中的项目,但您也可以解决它(告诉我您是否需要它,我会添加)

如果您重新加载它,它当然会删除检查。没有状态保存来避免它,您必须自己构造它(或者不清除它,只添加新项),当执行此操作时,我得到错误“'System.Windows.Forms.ListView.ListViewItemCollection'不包含'Exists'的定义,并且找不到接受'System.Windows.Forms.ListView.ListViewItemCollection'类型的第一个参数的扩展方法'Exists'(是否缺少using指令或程序集引用?)!listView1.Items.ToList().Exists(item=>item.Tag==nextRow)这对性能不好,但我只想知道这是否最终对youToList()起作用无法在之后使用。Items,因为它显然不允许我使用它。它无法完全工作。这会阻止我将新项目添加到ListView。我正在尝试找出一种方法,即使在我将更多项目添加到listbox时,它也会保持所有当前选中的项目处于选中状态,但感谢迄今为止的帮助:)我不明白。。。它也应该添加新项目,但不能重复。。。是否要有重复的值?
        TextReader reader = new StringReader(richTextBox1.Text);
        string[] strItems = null;
        while (reader.Peek() != -1)
        {
            string nextRow = reader.ReadLine();
            if (!listView1.Items.ContainsKey(nextRow.GetHashCode().ToString()))
            {
               ListViewItem item = new ListViewItem();
               item.Name = nextRow.GetHashCode().ToString();
               strItems = nextRow .Split("-".ToCharArray());
               item.Text = strItems[0].ToString();
               item.SubItems.Add(strItems[1].ToString());
               item.SubItems.Add(strItems[2].ToString());
               item.SubItems.Add(strItems[3].ToString());
               item.SubItems.Add(strItems[4].ToString());
               listView1.Items.Add(item);
            }
        }