试图从listview中删除行

时间:2017-12-01 11:33:55

标签: c# listview

我的代码根据文本框搜索条件正确识别列表视图行。但是,当我尝试删除不需要的行时,我收到一条错误消息: -

InvalidArgument ='-1'的值对'index'无效。

如果有人能帮我解决这个问题,我将非常感激..提前致谢。

  foreach (ListViewItem item in listView1.Items){
      foreach (ListViewItem.ListViewSubItem subItem in item.SubItems){
          if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
               var index = item.Index;
               int.TryParse(listView1.Items[index].SubItems[4].Text, out val);
               store[pos] = val;
               pos++;
               count++;
          }else{
               listView1.Items[index].Remove();
          }
      }
  }

3 个答案:

答案 0 :(得分:0)

问题在于,您不会在条款'其他'

中计算您的索引
}else{
           listView1.Items[index].Remove();
      }

答案 1 :(得分:0)

你不能从正在迭代Foreach的集合中删除项目,c#会因为集合发生变化而引发错误,而是用于代替,并从头到尾进行(所以你赢了#t; t删除时跳转项目

答案 2 :(得分:0)

尝试这种方法:

评论在代码中。如果您需要其他解释,请随时询问。

解决方案w / Linq

store

编辑:已删除的代码,它会删除以文本框开头的项目'文本(如OP想要的)。

编辑2:既然你不想使用Linq,你可以使用普通的旧列表和循环来解决你的问题

正如我在评论中所说,主要的是,在找到所有需要删除的项目之后,不要删除foreach循环内的项目。 代码经过测试和运行(没有4行,缺少变量val//list to hold intem indexes List<int> itemIndexes = new List<int>(); foreach (ListViewItem item in listView1.Items) { foreach (ListViewItem.ListViewSubItem subItem in item.SubItems) { var index = item.Index; if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower())) { //your code (which doesnt compile since you didn't paste whole code) //to test this, I had to remove following 4 lines. int.TryParse(listView1.Items[index].SubItems[4].Text, out val); store[pos] = val; pos++; count++; } else { itemIndexes.Add(index); } } } //lastly, sort indexes descending (for example: 10, 5,4,1) //because if you remove item 1, whole list will shorten and //you'll get index out of bounds error (in last step when //trying to remove item with 10 but last index is 7)... itemIndexes.Reverse(); //... and remove them from listview foreach (int index in itemIndexes) { listView1.Items.RemoveAt(index); } 等等。)

没有Linq的解决方案

a

使用示例数据进行测试 - 代码将删除不以bbb开头的项目,例如ddListView listView1 = new ListView(); listView1.Items.Add("aaa"); listView1.Items.Add("bbb"); listView1.Items.Add("ax"); listView1.Items.Add("dd"); TextBox textBox1 = new TextBox(); textBox1.Text = "a";

{{1}}
相关问题