user3828380
user3828380

Reputation: 35

c# index out of bound of array

This code gives me an error saying that the index is out of bounds of the array, but if I use MessageBox.Show() instead of ListBox.Items.Add() the error doesn't occur.

string[] arr = new string[gradeListbox.Items.Count];

for (int i = 0; i < gradeListbox.Items.Count; i++)
{
    arr[i] = gradeListbox.Items[i].ToString();
    Regex reg = new Regex(@"[0-9\.]+");
    grade = double.Parse(reg.Match(arr[i].ToString()).Value);
    studentName = Regex.Replace(arr[i], @"[\d-]", string.Empty);
    gradelistbox.Items.Add(grade + studentName);

    // ...
}

What is going on? How can I fix it so that it works with a ListBox?

Upvotes: 1

Views: 1568

Answers (2)

Nimesh
Nimesh

Reputation: 3620

Try to use AddRange method for addiing value in list

for more details read this below link

Why is AddRange faster than using a foreach loop?

Thanks -Nimesh

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

Your code keeps adding to gradelistbox.items thus increasing its count. The size of arr, on the other hand, remains the same. Therefore, you get an index out of bounds exception as soon as your loop gets to the original bounds of gradelistbox.items.

You can fix this problem by replacing the array arr with a container that can be resized dynamically - for example, List<string>. This would let you add items to arr each time that you add an item to gradelistbox.items, keeping their lengths the same.

Upvotes: 2

Related Questions