Wednesday, October 27, 2010

"Index was out of range" error when clicking on a column header in DataGridView

Problem
Clicking on a DataGridView column results in the error message "Index was out of range. Must be non-negative and less than the size of the collection."


Solution 
Make sure you are handling the CellContentClick (and other click events if appropriate) properly. Below is what I had
        private void gvBatches_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) //then they clicked on the link
            {
                //code that uses e.RowIndex
            }
        }

What this does is when the user clicks on the first column it proceeds to use e.RowIndex regardless of the value, because I assumed that a Column Header would not fire this event, but that's not the case. The e.RowIndex for a column header is -1, so make sure to check if e.RowIndex == -1. For example, i fixed mine and it looks like this now:
        private void gvBatches_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex != -1) //then they clicked on the link
            {
                //code that uses e.RowIndex
            }
        }

References
1. http://www.eggheadcafe.com/community/aspnet/14/10173997/index-out-of-range-error-when-clicking-the-column-header-in-datagridview.aspx 

No comments:

Post a Comment

There was an error in this gadget