Edwin Torres
Edwin Torres

Reputation: 483

IndexOutOfRangeException was unhandled- Index was outside the bounds of the array

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

Upvotes: 0

Views: 1699

Answers (3)

Ray K
Ray K

Reputation: 1490

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

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

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).

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

Upvotes: 2

Ravi Y
Ravi Y

Reputation: 4376

Your for loop should be changed to

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

Also, when you do the below line, make sure the index matches.

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

Because of your above error, it seems it does not match, You might be better off looping through your list view to find a matching ListView Item and then maniuplate it.

Upvotes: 0

MBen
MBen

Reputation: 3996

Well it is simple, your ListView.Items.Count is bigger then aa.Length. You need to make sure they have the same size.

Upvotes: 0

Related Questions