Search code examples
c#winformsdatagridviewdatagridviewcolumn

Sorting - headers Exception of DataGridView


I have a problem with sorting header of datagridview in windows form...

this is my code on CellContentClick

 private void dgvApprovazione_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell)
        {//Process link on string
            System.Diagnostics.Process.Start(dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string);
        }
    }

my datagridview result .. enter image description here

but when i click on header columns i have this exception : enter image description here

how to resolve it ?


Solution

  • You should check if the clicked cell is not in header row, otherwise when you try to access the cell of the that row, you receive an ArgumentOutOfRangeException because you tried to get cell at RowIndex = -1.

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

    You need to check if (e.RowIndex>=0)