I have a for loop that adds items in an array to a listView.
(It’ll grab items on a webpage, remove anything after the ‘ in the string, then add it to the listView)
The error I am getting is: IndexOutOfRangeException was unhandled- Index was outside the bounds of the array
Here’s the code I am using:
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);
}
The error occurs on this line: string input = aa[i];
Anything I did wrong? How can I fix this issue so it’ll stop happening? Thanks!
If you’re wondering the code for the getBetweenAll method is:
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();
}
Your looping the elements of ‘listView1’
If the item count of listView1 exceeds the number of elements of the string array ‘aa’ you will get this error.
I would either change the loop to be
or inside your for loop put an if statement to make sure that you are not exceeding the elements of aa. (although, I doubt this is what you want to do).