CellContentClick throws ArgumentOutOfRangeException when user clicks on the column header

Problem

In a WinForm project, you’re using a DataGridView control and are handling the CellContentClick event. When the user clicks the column header, the following exception is thrown:

System.ArgumentOutOfRangeException: ‘Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index’

The problem is that when the user clicks the column header, it’s firing the CellContentClick event and the value of DataGridViewCellEventsArg.RowIndex is -1. In your CellContentClick handler, you’re using the RowIndex value to index an array. Hence, the index out of range exception.

Solution

In your CellContentClick event handler, check if they clicked the column header and do nothing, like this:

private void dataGrid_OnCellContentClick(object sender, DataGridViewCellEventArgs e) { var grid = (DataGridView)sender; if (e.RowIndex < 0) { return; } if (grid[e.ColumnIndex, e.RowIndex] is DataGridViewLinkCell linkCell) { var linkUrl = linkCell.Value.ToString(); //Open link in browser } }
Code language: C# (cs)

Leave a Comment