I can't figure out why I'm getting the out of range exception on the follow开发者_StackOverflowing piece of code. The values for _maxRowIndex
and _maxColIndex
are 5
, and 0
respectively. The exception is being thrown on the first time through when row
and col
are both equal to 0
. I don't understand why 0, 0
would be out of bounds on the array.
_cells = new ToolBarButton[_maxRowIndex, _maxColIndex];
.
.
.
for (int col = 0; col <= _maxColIndex; col++) {
for (int row = 0; row <= _maxRowIndex; row++)
{
if (_cells[row, col] == null)
{
PopulateCell(toolBarbutton, row, col);
}
}
}
Array indices start from 0 and are upto [upperbound-1]. Since your loop starts at 0, it must end at < the limit value rather than <= limit value. So, change the "<=" to "<" in the loop. Eg:
col <= _maxColIndex
should be changed to
col < _maxColIndex
If you want the max index to be 5, that means the array needs to be of length 6 as the first element is at index 0.
So, change:
_cells = new ToolBarButton[_maxRowIndex, _maxColIndex];
to:
_cells = new ToolBarButton[_maxRowIndex+1, _maxColIndex+1];
You have <= in your for statement...
So your loop evaluates for col =0, 1, 2, 3, 4 and 5... 5 is out of bounds
I guess you should declare _cells as below
_cells = new ToolBarButton[5,1];
instead of
_cells = new ToolBarButton[5,0];
精彩评论