G. Soós
G. Soós

Reputation: 47

Datagridview clicked header first cell exception

I have a big problem. I ran into it while developing a windows-form application. I placed a datagridview with 4 columns and a few rows on the form. When I click on the header of the first column it throws an error message. I also attached this. I tried to specify a condition for the "CellClick" event so as not to cause a problem. Unfortunately, he didn't solve it. Strange because this error phenomenon is not present in the additional columns. Whatever I tried and modified I couldn’t eliminate. Sorry for my English. CellClick event handler code:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex == -1)
            return;
    }

Upvotes: 0

Views: 735

Answers (1)

TnTinMn
TnTinMn

Reputation: 11801

I suspect that first column is used to display DateTime values and that the DataGridViewColumn.SortMode Property is set to DataGridViewColumnSortMode.Automatic. When you click on the column header, the DGV tries to sort the column.

The problem is that in one or more rows the value stored in cell[0] is not either a DateTime value or null. This is why you are receiving the error message of:

System.ArgumentException: 'Object must be of type DateTime.'

If you do not want the column to automatically sort, set the SortMode property to either DataGridViewColumnSortMode.NotSortable or DataGridViewColumnSortMode.Programmatic.

Upvotes: 1

Related Questions