Index was outside the bounds of the array.

gprabaka

Newcomer
Joined
Jul 14, 2005
Messages
21
All,

When it hits the Bold line, I get the error, Index was outside the bounds of the array.
Anyone know what I need to know.
Thanks
Guha
<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>

DataGridViewCell[,] cells = new DataGridViewCell[15, 1];
foreach (DataGridViewCell cell in selectedCells)
{
cells[0, 1].Value = cell.value;

}
 
Last edited:
If you create an array with code like
C#:
DataGridViewCell[,] cells = new DataGridViewCell[15, 1];
The maximum element number in each dimension is one less than you specify (arrays are counted from 0 not 1), therefore the maximum element is at position [14,0] - which is really the same as creating a single dimension array.
 
Mr. PlausiblyDamp,
Are you saying that I need to start populating from cells[0,0] and not from cells[0,1]?
Thanks
Guha
 
Yup. You start counting from zero. The numbers in the square bracket only tell how many elements you want in your array. So, if you have 1 element and you start counting from 0, the only valid index is 0. If you have 15 elements and start counting from 0, the only valid elements are 0-14.

But, as PlausiblyDamp said, you might as well use a single dimension array in this case since it's really a 15x1 array already.

edit: I just read over the code I wrote and realized it made no sense. I must have had something else going on in my head at the time. I've removed it to avoid confusion.
 
Last edited:
After you change the code to use 0,0 I think you may get a NullReferenceException. You'll get that if DataGridViewCell is a reference type. The reason is that when you create a new array of a reference type, you have to instantiate each element in that array. For example:
C#:
DataGridViewCell[,] cells = new DataGridViewCell[15, 1];
foreach (DataGridViewCell cell in selectedCells)
{
    cells[0, 0] = new DataGridViewCell();
    cells[0, 0].Value = cell.value;
}

Of course, it looks like you want the value out of a cell, which is probably of type object or string. In that case, it makes more sense to do this:'
C#:
string[,] cells = new string[15, 1];
foreach (DataGridViewCell cell in selectedCells)
{
    cells[0, 0] = cell.value.ToString(); // May STILL blow up if value is "null"
}

-ner
 
Back
Top