Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items in ListView

I've got a loop in a button action for removing empty items in my ListView, but the problem is, when I press the button it deletes successfully only the items that were single. I mean: it does not remove items, when there are few one after another:

example:

a1 = ""
a2 = "qwe"
a3 = ""
a4 = ""
a5 = "qwe"

so, after button click, the result will be:

a2 = "qwe"
a3(or a4 idk) = ""
a5 = "qwe"

I think it's easy logic problem, but I can't figure it out.

for (int i = 0; i < listView1.Items.Count; i++) 
            {
                if (listView1.Items[i].SubItems[2].Text == "")
                {
                    listView1.Items[i].Remove();
                }
            }

So the problem is that the loop skips one check after it finds the empty value. How do I fix it?

like image 359
Denis Wasilew Avatar asked Feb 19 '16 15:02

Denis Wasilew


1 Answers

When removing items in a for loop, loop backward:

for (int i = listView1.Items.Count - 1; i >= 0; --i) 
  if (listView1.Items[i].SubItems[2].Text == "")
    listView1.Items[i].Remove();

or modify the for loop into

for (int i = 0; i < listView1.Items.Count; ) // no ++i here
  if (listView1.Items[i].SubItems[2].Text == "")
    listView1.Items[i].Remove();
  else  
    i += 1; // ...but it's here

This is a common principle beyond ListView items. See what's getting on: imagine that you want remove A from the collection

  [A, A, B, A] 

when you've found that's 0th item must be deleted, you should not increment counter after deletion, but test new 0th item again.

like image 60
Dmitry Bychenko Avatar answered Oct 13 '22 12:10

Dmitry Bychenko