C# – DataGridView index out of range exception


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.


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)

	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