DataGridView index out of range exception
By FoxLearn 2/4/2025 9:05:32 AM 92
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#