1

I have the following piece of code getting values from a Listbox. I've three teachers selected. when 'i' value reaches 3 it shows'Index was outside the bounds of array' error

    string selectedTeachers = Request["SelectedTeachersList"];
    int[] teachers_ID = Array.ConvertAll(selectedTeachers.Split(','), int.Parse);
    for (int i = 0; i <= teachers_ID.Length; i++)
    {
      int Id = teachers_ID[i];
    }
kakkarot
  • 478
  • 1
  • 9
  • 24
Y2J
  • 41
  • 1
  • 8

3 Answers3

5

Arrays are zero based index, the first element in array will have zero index and last will have one less then size of array so it must be one less then the length of arry.

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

C# arrays are zero indexed; that is, the array indexes start at zero.

Read more about the arrays in MSDN Arrays Tutorial

Adil
  • 146,340
  • 25
  • 209
  • 204
2

You should do

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

(smaller to and smaller-or-equal operator)

If an array has 10 elements, you access them from index 0 to 9. Therefore, the for clause should exit, when i == 10. In your code, i==10 is still executed and then you obviously get an exception.

marco
  • 685
  • 4
  • 18
1

Use foreach here which is simple to use

foreach(int i in teachers_ID)
    int Id = i;

You need not worry about the number of elements in the array in this case. You got 'Index was outside the bounds of array' error because C# arrays are zero indexed.

kakkarot
  • 478
  • 1
  • 9
  • 24