DataGridView index out of range exception

By FoxLearn 2/4/2025 9:05:32 AM   92
While working with WinForms in C#, you may encounter an issue when clicking on a column header in a DataGridView.

You might see an error like:

Index was out of range. Must be non-negative and less than the size of the collection.

This exception is often caused by the DataGridView triggering a click event on the column header, which is considered a "row" with an invalid index. Specifically, the RowIndex in the event arguments will be set to -1. When you attempt to use this invalid value, such as trying to retrieve a specific cell that was clicked, it results in the "index out of range" exception.

The Cause

The issue occurs because column header clicks don't represent a valid row in the DataGridView. Therefore, the RowIndex is -1 when a header is clicked, leading to the exception if you attempt to access the clicked cell.

Solution

To prevent this exception, you can add a check in the click event handler to verify that the RowIndex is not less than zero. Here's a modified version of the CellContentClick event handler that includes the necessary guard:

private void dataGrid_OnCellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var grid = (DataGridView)sender;

    // Check if the clicked event was on a valid row
    if (e.RowIndex < 0)
    {
        return;  // Skip if the RowIndex is invalid
    }

    // Handle clicks on DataGridViewLinkCell (for example, opening a link)
    if (grid[e.ColumnIndex, e.RowIndex] is DataGridViewLinkCell linkCell)
    {
        var linkUrl = linkCell.Value.ToString();
        // Open the link in a browser or handle it as needed
    }
}

Before doing any operations with the clicked cell, check if the RowIndex is greater than or equal to 0. If it's less than 0 (indicating a column header was clicked), simply return from the method to avoid further processing.