This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
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];
}
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
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.
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.
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 8 months ago.
got datagridview with 3 data, I want to get the first cells data on each rows, when I use this kind of code
string[] DataGridViewArray = { };
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
DataGridViewArray[i] = DataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
}
textBox1.Text = DataGridViewArray.ToString();
why it keep said 'Index was outside the bounds of the array.'
Array is fixed size and its size is determined when declaring it (eg. in your first line of code) .
However, you gave it no single element nor set its size with expected number of items its going to hold - which in your case should be DataGridView1.Rows.Count.
string[] DataGridViewArray = { };
Instead, if you replace that (line #1 code) as follows, it should work:
string[] DataGridViewArray = new string[DataGridView1.Rows.Count];
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
DataGridViewArray[i] =
DataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
}
textBox1.Text = DataGridViewArray.ToString();
I don't have DataGridView1 but I did something similar just to show you the reason why you are getting out of index error and how to fix it.
Clostly look at the length of the array in a way you defined it vs when array length is provided when declaring it.
It's because you didn't properly instantiate your array so any iteration will be out of bounds.
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I have the following array:
public int[] ID = {0,1,2,3,4};
I´m calling the following method, which contains an get-method in an framework:
int[] marker = this.m_TuioManager.getID(this.ID);
Get-Method in the framwork class:
public int[] getID(int[] wert)
{
int number= 4;
for (int i = 0; i<=number; i++)
{
for (int j = 0; j<=number; j++)
{
wert[i] = wert[j];
}
}
return wert;
}
The exception is:
Array index out of range
which I don´t understand. Cauze my array has 5 numbers from 0 to 4. And in the for loop I´m iterating until 4.
What I want later, is to compare the values in the array like wert[0] = 0, wert[1] = 1 and so on(until 4),with an other variable.
If you want to avoid "Array index out of bounds" errors, don't write code that assumes arrays always have X number of elements. Either check the .Length of the array before you attempt to access 4 elements of it, or write a loop that runs to the array.Length rather than always running to a fixed 4 elements
if(array.Length < 4)
throw new Exception("min array length is 4, you passed " + array.Length);
Or
for(int i = 0; i < array.Length; i++)
Or
foreach(int i in array)
If you can get any of these lines of code to crash with an AIOOB exception, inform Microsoft
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
I'm getting one of the following errors:
"Index was out of range. Must be non-negative and less than the size of the collection"
"Insertion index was out of range. Must be non-negative and less than or equal to size."
"Index was outside the bounds of the array."
What does it mean, and how do I fix it?
See Also
IndexOutOfRangeException
ArgumentOutOfRangeException
Why does this error occur?
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.
How indexing arrays works
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.
How other collections work
Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
I'm getting one of the following errors:
"Index was out of range. Must be non-negative and less than the size of the collection"
"Insertion index was out of range. Must be non-negative and less than or equal to size."
"Index was outside the bounds of the array."
What does it mean, and how do I fix it?
See Also
IndexOutOfRangeException
ArgumentOutOfRangeException
Why does this error occur?
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.
How indexing arrays works
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.
How other collections work
Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
This question already has answers here:
Finding position of an element in a two-dimensional array?
(2 answers)
Closed 9 years ago.
Is there a slicker way? After populating the array with random numbers (and where the user determines the size of the 2D array) I got the max like this:
int largest = array.Cast<int>().Max();
Now to get the index values, the only way I could think was to do this:
for (int i = 0; i < rowsize); i++) {
for (int j = 0; j < columnsize); j++) {
if (largest == array[i, j])
Console.WriteLine("The index values of the largest value are {0} and {1}", i, j);
}
}
I was thinking there was a way to use the IndexOf method, couldn't find it. And I could be wrong, but a foreach loop doesn't seem to support index values.
There is a chance for duplicated max values in your current situation. You could probably save yourself half a millisecond saving the message to be displayed to a local variable and printing this after the loop in the form of message1\r\n\message2\r\n\r\nmessage3. However if you're only interested in the first occurance breaking from the loop might be worth considering.
Either way, you're basically fine.