Ben
Ben

Reputation: 4319

Can't remove items from WinForms ListView

I have two ListViews and want to move items from one to the other.

I can copy to the new list, but the remove from the first list doesn't work.

private void button2_Click(object sender, EventArgs e)
{
    foreach (ListViewItem i in listView1.Items)
    {
        if (i.Checked == true)
        {
            ListViewItem itemClone = i.Clone() as ListViewItem;
            listView2.Items.Add(itemClone);
        }
    }    
    foreach (ListViewItem itemSelected in listView1.SelectedItems)
    {
        listView1.Items.Remove(itemSelected);
    }

    listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
    listView2.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}

It's a bit inelegant at the moment with two loops, but one post I read said I couldn't add and remove an item in the same foreach loop.

Upvotes: 0

Views: 231

Answers (2)

shadow
shadow

Reputation: 1903

I believe that you want to remove the checked items since they moved to the second list view. So try this:

        private void button1_Click(object sender, EventArgs e)
        {
            listView1.BeginUpdate();
            listView2.BeginUpdate();

            var checkedItems = new List<ListViewItem>();

            foreach (ListViewItem li in listView1.CheckedItems)
            {
                checkedItems.Add(li.Clone() as ListViewItem);
                listView1.Items.Remove(li);
            }

            listView2.Items.AddRange(checkedItems.ToArray());

            listView1.EndUpdate();
            listView2.EndUpdate();
        }

Upvotes: 0

MrGoodbytes
MrGoodbytes

Reputation: 294

You used SelectedItems, not CheckedItems, on the second loop.

Upvotes: 2

Related Questions