简体   繁体   中英

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]);

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM