开发者

Specified items will not be deleted when using ListView.Item.RemoveAt()

开发者 https://www.devze.com 2023-01-22 17:22 出处:网络
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.

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

Specified items will not be deleted when using ListView.Item.RemoveAt()

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);
        }
    }


See MSDN in the Remarks section.

When you remove an item from the collection, the indexes change for subsequent items in the collection. All information about the removed item is deleted. You can use this method to remove a specific item from the collection by specifying the index of the item to remove from the collection. To specify the item to remove instead of the index to the item, use the Remove method. To remove all items from the collection, use the Clear method.

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.

    for (int i = 0; i < listView1.Items.Count; i++)
    {
        if (listView1.Items[i].SubItems[0].Text == "A1")
        {
            listView1.Items.RemoveAt(i);
            i--; // Back counter up one
        }
    }


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:

private void button1_Click(object sender, EventArgs e)
{
    var itemsToRemove = new List<ListViewItem>();

    foreach (ListViewItem item in listView1.Items)
    {
        if (item.SubItems[0].Text == "A1")
            itemsToRemove.Add(item);
    }

    foreach (var item in itemsToRemove)
        listView1.Items.Remove(item);
}

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消