Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

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;

 

}

Edited by gprabaka
  • Administrators
Posted

If you create an array with code like

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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted (edited)

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.

Edited by mskeel
  • *Experts*
Posted

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:

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:'

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

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...