单击标题时gridview中的nullreferenceexception

时间:2013-03-15 05:24:47

标签: vb.net datagridview nullreferenceexception

在我的DataGridView selectionChange中我有这个代码,所以当行改变时,texbox也会改变。下面的代码工作,我点击该行,它显示正确,当我按向上/向下箭头。我的问题是当我点击网格的Header中的somwhere时,我有这个nullreferenceexception错误Object reference not set to an instance of an object.。我不知道如何处理它,因为我知道它返回了什么。

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

1 个答案:

答案 0 :(得分:1)

无论何时获得没有选择ROW的RowIndex,都会引发空引用 单击标题会调用SORT,这会清除选择 这将帮助您摆脱空引用异常

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

代码:

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