I have a listview with two columns and I'm using a context menu to allow users to remove selected rows. To remove the selected rows, I've tried with the following code but it doesn't work:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
listView1.SelectedItems.Clear();
}
I suspect this is because the listview has two columns, but I can't figure out a solution to remove selected rows. Removing all rows works with: listView1.Items.Clear();.
-
This seems to work:
for (int i = 0; i < listView1.Items.Count; i++ ) { if (listView1.Items[i].Selected) { listView1.Items[i].SubItems.Clear(); } }Is there any way to remove items and re-order the listView so that there are no empty rows in the middle of other rows?
-
This seems to be a better solution:
for (int i = 0; i < listView1.Items.Count; i++ ) { if (listView1.Items[i].Selected) { listView1.Items[i].Remove(); } } -
What you can do:
foreach (ListViewItem Item in LstvClients.Items) { if (item.Selected) { LstvClients.Items.Remove(Item); } }(Yours is better, item.Remove())
BFree : Actually, this won't move. You can't mess with a collection while you're iterating over it.BeefTurkey : But it seems to work.PoweRoy : BFree: Yes it looks weird but it works -
The latest example of BeafTurkey looks correct, but he should decrement i after removing the item:
for (int i = 0; i < listView1.Items.Count; i++ ) { if (listView1.Items[i].Selected) { listView1.Items[i].Remove(); i--; } }The index of items larger as i is decremented by 1 after the removal. So you should reposition i to match the next not tested item.
BeefTurkey : didn't think of that - thank you.
0 comments:
Post a Comment