C#:Index超出了ListView的数组范围

时间:2012-11-17 17:52:47

标签: c# arrays forms listview

我一直得到“索引超出了数组的范围。”当我尝试将项目添加到listView。

我做错了什么?

这是我的代码:

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

此行显示错误:

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

1 个答案:

答案 0 :(得分:1)

请注意,您在h.Length循环中使用u.Length而不是for作为条件。您正在添加u而不是h的元素,并且很可能u.Length小于h.Length,并且当您尝试访问u [i]时会出现异常。它应该是:

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