gprabaka Posted July 20, 2006 Posted July 20, 2006 (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 July 20, 2006 by gprabaka Quote
Administrators PlausiblyDamp Posted July 20, 2006 Administrators Posted July 20, 2006 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
gprabaka Posted July 20, 2006 Author Posted July 20, 2006 Mr. PlausiblyDamp, Are you saying that I need to start populating from cells[0,0] and not from cells[0,1]? Thanks Guha Quote
mskeel Posted July 20, 2006 Posted July 20, 2006 (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 July 21, 2006 by mskeel Quote
*Experts* Nerseus Posted July 21, 2006 *Experts* Posted July 21, 2006 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 Quote "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
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.