使用ListView.Item.RemoveAt()时不会删除指定的项目
我尝试使用 RemoveAt()
方法从列表视图中删除特定项目。但是当我第一次删除它时,有些项目会保留下来。
例如:见下图
代码:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[0].Text == "A1")
{
listView1.Items.RemoveAt(i);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 0; i<3; i++)
{
ListViewItem lvi = new ListViewItem("A1");
lvi.SubItems.AddRange(new string[] {"desc" + i.ToString(), i.ToString()});
listView1.Items.Add(lvi);
}
for (int i = 0; i < 2; i++)
{
ListViewItem lvi = new ListViewItem("A2");
lvi.SubItems.AddRange(new string[] { "desc" + i.ToString(), i.ToString() });
listView1.Items.Add(lvi);
}
}
I have tried to remove specific items from a listview using the RemoveAt()
method. But When I remove it the first time some items will stay.
For example: see the image below
Code:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[0].Text == "A1")
{
listView1.Items.RemoveAt(i);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 0; i<3; i++)
{
ListViewItem lvi = new ListViewItem("A1");
lvi.SubItems.AddRange(new string[] {"desc" + i.ToString(), i.ToString()});
listView1.Items.Add(lvi);
}
for (int i = 0; i < 2; i++)
{
ListViewItem lvi = new ListViewItem("A2");
lvi.SubItems.AddRange(new string[] { "desc" + i.ToString(), i.ToString() });
listView1.Items.Add(lvi);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅 MSDN 中的 < em>备注部分。
编辑:参见Moot的回答。上面的链接/参考也适用于他/她的答案。
编辑 2:
如果找到匹配项,只需将计数器加一即可。
See MSDN in the Remarks section.
Edit: See Moot's answer. Link / reference above applies to his/her answer as well.
Edit 2:
Just back the counter up one if you find a match.
当您删除第一个 A1 时,列表会缩小,1 和 2 处的元素将成为 0 和 1 处的元素。因此,当循环递增时,它会删除 1 处的 A1(第三个)并跳过移动的元素降至 0。
When you delete the first A1, the list shrinks, and the element at 1 and 2 become your element at 0 and 1. So, when your loop increments, it deletes the A1 at 1 (the third one) and skips the one which moved down to 0.
执行以下操作:
祝你好运!
Do the following:
Good luck!