C# – DataGridView index out of range exception

Problem

When you’re using WinForms and click a DataGridView column header, you get an exception like this:

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

This problem is caused by the column header “row” triggering a click event (such as CellContentClick) with event args containing RowIndex of -1. When you try to use this invalid index value (like to get the DataGridView cell that was clicked), it throws the exception.

Solution

In the click event handler, guard against the exception by checking if RowIndex < 0 before attempting to use it, 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)