1

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?

user3828380
  • 35
  • 1
  • 6
  • 1
    `gradelistbox.Items.Add = grade + studentName` is still invalid. if it is to be a string that is added, try: `gradelistbox.Items.Add(grade + studentName);` – czifro Jul 29 '14 at 04:04

2 Answers2

2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • is there a way to delete the list you've already processed? For example, after you finished looping the 1st line of list box, delete that line. – user3828380 Jul 29 '14 at 04:13
  • @user3828380 Yes, this is possible, but managing indexes becomes a nightmare. You would be better off creating a separate list on the side, writing it in a loop, and then replacing the original with it after the loop is done. – Sergey Kalinichenko Jul 29 '14 at 04:20
0

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

Community
  • 1
  • 1
Nimesh
  • 3,342
  • 1
  • 28
  • 35