DataGridView. Handling selection changed event when column header is clicked

AndyNakamura 51 Reputation points
2021-05-29T08:36:09.49+00:00

I have some code in the selection changed event for my datagridview control.
It just gets the value in a particular cell in the current row and puts the value in a textbox.

Try
TxtOpNotes.Text = DataGridView1.CurrentRow.Cells(10).Value
Catch ex As Exception

            MsgBox(ex.ToString)
        End Try

However, the app throws an exception if the user clicks on the column header:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Forms.DataGridView.CurrentRow.get returned

I've tried

If DataGridView1.CurrentRow.Index = -1 Then
            Exit Sub
        End If

But I get the same exception.

Anyone know how to get out of this. It doesn't seem possible to disable the column header mouse click

Developer technologies VB
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-05-29T08:50:30.453+00:00

    Try adding this line: If DataGridView1.CurrentRow Is Nothing Then Exit Sub.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.