Priscila
Priscila

Reputation: 301

ListViewSubItems in C#

I want to delete some ListViewSubItem if they are checked. I want to remove them from the ListView and from a list (List Products) by the sku. I´m getting an ArgumentOutOfRangeException if I add 1 to the ListViewSubItem´s index and if I dont´t, I can´t delete the first subitem. Pl hlp. Thanks. My code:

 int count = lv_list.Items.Count;
 for (int j = count - 1; j >= 0; j--)    
 if (lv_list.Items[j].Checked)
 {
    sku = lv_list.Items[j].SubItems[j+1].Text; 
    lv_list.Items[j].Remove();
    DeleteProductBySKU(sku);
  }

Upvotes: 0

Views: 67

Answers (1)

user2480047
user2480047

Reputation:

As pointed out via comments, j+1 is a wrong index for SubItems. What you know for sure is that j is a valid index for Items, but don't have any information about the corresponding SubItems (if j+1 or even j are valid). A quick fix avoiding errors:

for (int j = count - 1; j >= 0; j--)
    if (lv_list.Items[j].Checked)
    {
        if (lv_list.Items[j].SubItems.Count - 1 >= j + 1) //lv_list.Items[j].SubItems.Count - 1 -> last index of SubItems
        {
            sku = lv_list.Items[j].SubItems[j + 1].Text;
        }
        else
        {
            sku = lv_list.Items[j].SubItems[lv_list.Items[j].SubItems.Count - 1].Text;
            //sku = lv_list.Items[j].SubItems[0].Text -> to choose the first SubItem
        }
        lv_list.Items[j].Remove();
        DeleteProductBySKU(sku);
    }

The code above takes the last SubItem in case that j+1 is not a valid index. It avoids errors but I guess that this is not what you are looking for. You should update the code to modify the SubItem you really want (which should either be a constant value or defined by another counter different than j).

Upvotes: 2

Related Questions