1

I can't figure out why I'm getting the out of range exception on the following 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);
                        }

                    }
                }

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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];

2 Comments

Or, do what Mamta suggested. It depends on whether you want there to be 5 items in your list, or the last item to be at index 5.
I want the last index to be 5 for a total of 6 items in the list. I didn't occur to me that the declaration was for total elements, not highest index. I made the change that you suggested and it works the way I want it to now.
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

Comments

1

I guess you should declare _cells as below

_cells = new ToolBarButton[5,1];

instead of

_cells = new ToolBarButton[5,0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.