Removing Items in a ListView

I have a loop in the action of the button to delete empty items in my ListView , but the problem is that when I click the button, it successfully deletes only those items that were single. I mean: it does not delete elements when there are several of them:

Example:

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

therefore, after clicking the button, the result will be:

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

I think this is an easy logical problem, but I cannot figure it out.

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

Thus, the problem is that the loop skips one check after it finds an empty value. How to fix it?

+5
source share
1 answer

When deleting items in a for loop , backtracking:

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

or change the for loop to

 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 here 

This is a general principle that goes beyond ListView . Look what happened: Imagine you want to remove A from the collection

  [A, A, B, A] 

when you find that the 0th item needs to be deleted, you should not increment the counter after deleting, but you are testing the new 0th item again.

+4
source

Source: https://habr.com/ru/post/1243407/


All Articles