1

In my DataGridView selectionChange i have this code, so when the row change the texbox also changes. the code below works, i click the row and it displays right, also when i press up/down arrows. My problem is when I click somwhere in the Header of the grid i have this nullreferenceexception error Object reference not set to an instance of an object.. I don't have idea how to handle it, since i down know what it returns.

Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
    Dim index As Integer
    index = DataGridView1.CurrentCell.RowIndex '<<<<--problem here when I click the header
    If (index <= maxrows - 1) Or (index <> Nothing) Then
        TextBox2.Text = DataGridView1.Item(1, index).Value()
        TextBox3.Text = DataGridView1.Item(2, index).Value()
        TextBox4.Text = DataGridView1.Item(3, index).Value()
    End If
End Sub
4

1 回答 1

1

A null reference is raised whenever you get the RowIndex wherein there is no ROW is selected.
Clicking the header calls SORT and this clears the selection.
This will help you get rid of the nullreference exception

    If DatagridView1.SelectedRows.Count = 0 Then
        Msgbox "Nothing Selected"
        Exit Sub 'Trapping
    End If

Code:

Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
    If DatagridView1.SelectedRows.Count = 0 Then
        Msgbox "Nothing Selected"
        Exit Sub 'Trapping
    End If

    Dim index As Integer
    With DataGridView
        index = .CurrentRow.RowIndex
        If (index <= maxrows - 1) Then
            TextBox2.Text = .Item(1, index).Value()
            TextBox3.Text = .Item(2, index).Value()
            TextBox4.Text = .Item(3, index).Value()
        End If
    End With
End Sub
于 2013-03-15T05:42:48.547 回答