从vb.net 2012上的数据gridview获取行数据

时间:2013-04-28 09:40:25

标签: vb.net

我想从DataGridView的1行获取数据,我选择了我的文本框 这是我的代码,

Private Sub DataGridView1_CurrentCellChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellChanged

    Dim dColums(0) As DataColumn
    dColums(0) = dsetmember.Tables("member").Columns(0)
    dsetmember.Tables("member").PrimaryKey = dColums

    'MessageBox.Show(DataGridView1.CurrentRow.Index, 1)
    If DataGridView1.CurrentRow.Index = -1 Then
        txtNamaMember.Text = ""
        txtKodeMember.Text = ""
        txtNoHP.Text = ""
    Else
        Dim dr As DataRow = dsetmember.Tables("member").Rows.Find(DataGridView1.Item(DataGridView1.CurrentRow.Index, 0))
        txtKodeMember.Text = dr(0)
    End If

End Sub

我收到此错误,nullreferenceException was unhandled Object reference not set to an instance of an object.

thx b4。

2 个答案:

答案 0 :(得分:0)

错误发生在dr(0)到textbox.Text的转让中 这意味着Find方法未找到传递的值,因此结果为NULL。 当dr是Nothing时试图引用dr(0)就像写NOTHING(0),当然,这将失败

Dim dr As DataRow = dsetmember.Tables("member").Rows.Find(DataGridView1.Item(DataGridView1.CurrentRow.Index, 0))
if dr IsNot Nothing then
    txtKodeMember.Text = dr(0)
else
    MessageBox.Show("Value not found")
End If

还要记住,Find方法搜索在表的主键列上传递的值。您确定网格的第一列包含主键吗?

答案 1 :(得分:0)

尝试更改此部分..

If DataGridView1.CurrentRow.Index = -1 Then
    txtNamaMember.Text = ""
    txtKodeMember.Text = ""
    txtNoHP.Text = ""
Else
    Dim dr As DataRow = dsetmember.Tables("member").Rows.Find(DataGridView1.Item(DataGridView1.CurrentRow.Index, 0))
    txtKodeMember.Text = dr.item(0)
End If