Edwin Torres
Edwin Torres

Reputation: 483

C#: Index was outside the bounds of the array with ListView

I keep getting "Index was outside the bounds of the array." when I try to add items to a listView.

What am I doing wrong?

Here is my code:

 string[] h = getBetweenAll(thepage, "\" target=\"_blank\">", "</a>");
         foreach (string s in h)
         listViewClickbank.Items.Add(new ListViewItem(""));

        foreach (ListViewItem i in listViewClickbank.Items)
         {
           if (i.SubItems[0].Text == "(view mobile)")
          {
                i.Remove();
           }
       }

      foreach (ListViewItem i in listViewClickbank.Items)
     {
             if (i.SubItems[0].Text.Contains("recordTitle"))
           {
             i.Remove();
          }
      }

      string[] u = getBetweenAll(thepage, "<div class=\"description\">", "</div>");
      for (int i = 0; i < h.Length && i < listViewClickbank.Items.Count; i++)
      {
           listViewClickbank.Items[i].SubItems.Add(u[i]);
      }

The error appears on this line:

listViewClickbank.Items[i].SubItems.Add(u[i]);

Upvotes: 0

Views: 548

Answers (1)

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

Note that you are using h.Length, not u.Length as a condition in your for loop. You are adding elements of u, not h and most probably, u.Length is smaller than h.Length and you get Exception when you try to access u[i]. It should be :

string[] u = getBetweenAll(thepage, "<div class=\"description\">", "</div>");
for (int i = 0; i < u.Length && i < listViewClickbank.Items.Count; i++)
{
     listViewClickbank.Items[i].SubItems.Add(u[i]);
}

Upvotes: 1

Related Questions