JavaEar 专注于收集分享传播有价值的技术资料

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?


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

  2. 参考答案2