2012-11-23 50 views
-1

我有一个for循环,将数组中的项添加到listView。IndexOutOfRangeException was unhandled-索引超出了数组的边界

(它会抢在网页上的项目,之后删除任何东西“的字符串,然后将它添加到ListView)

我得到的错误是:IndexOutOfRangeException was unhandled- Index was outside the bounds of the array

这里是我的代码现在用:

string[] aa = getBetweenAll(vid, "<yt:statistics favoriteCount='0' viewCount='", "'/><yt:rating numDislikes='"); 
for (int i = 0; i < listView1.Items.Count; i++) 
{ 
    string input = aa[i]; 
    int index = input.IndexOf("'"); 
    if (index > 0) 
     input = input.Substring(0, index); 
    listView1.Items[i].SubItems.Add(input); 
} 

出现的错误在这条线:string input = aa[i];

什么我做错了什么?我该如何解决这个问题,以便它会停止发生?谢谢!

如果你想知道的getBetweenAll方法的代码是:

private string[] getBetweenAll(string strSource, string strStart, string strEnd) 
{ 
    List<string> Matches = new List<string>(); 

    for (int pos = strSource.IndexOf(strStart, 0), 
     end = pos >= 0 ? strSource.IndexOf(strEnd, pos) : -1; 
     pos >= 0 && end >= 0; 
     pos = strSource.IndexOf(strStart, end), 
     end = pos >= 0 ? strSource.IndexOf(strEnd, pos) : -1) 
    { 
     Matches.Add(strSource.Substring(pos + strStart.Length, end - (pos + strStart.Length))); 
    } 

    return Matches.ToArray(); 
} 
+0

请出示什么getBetweenAll的方法或函数看起来像 – MethodMan

+0

@DJKRAZE我张贴现在 –

回答

1

你的循环“ListView1的”

如果ListView1的的项目数超过了字符串数组的元素数量的元素“AA”,你会得到这个错误。

我要么改变循环是

for(..., i < aa.Length, ...) 

或者你在for循环中把一个if语句,以确保您不会超过AA的元素。 (虽然,我怀疑这是你想要做的)。

for (int i = 0; i < listView1.Items.Count; i++) 
{ 
    if(i < aa.Length) 
    { 
     string input = aa[i]; 
     int index = input.IndexOf("'"); 
     if (index > 0) 
     input = input.Substring(0, index); 
     listView1.Items[i].SubItems.Add(input); 
    } 
} 
+0

怎么会if语句是什么样子?我将for循环更改为aa.Length,但随后在代码的另一部分中出现错误。 –

+0

感谢您的帮助雷:) –

0

那么它很简单,你的ListView.Items.Count是更大然后aa.Length。你需要确保它们具有相同的尺寸。

0

您的循环应改为

for (int i = 0; i < aa.Length; i++) 

而且,当你做下面的线,确保指数的匹配。

listView1.Items[i].SubItems.Add(input); 

因为你上面的错误,似乎不匹配,你可能会更好过你的列表视图循环查找匹配的ListView项,然后maniuplate它。

相关问题