VB.NET将数据库中的数据显示给Datagridview

时间:2016-04-14 09:37:52

标签: vb.net datagridview

当我想将数据库中的数据显示到datagridview时,我收到以下错误:

  

对象引用未设置为对象的实例

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    connect()
    Try
        strsql = "select * from tbInfo"
        cmd.CommandText = strsql
        Dim da As New OleDbDataAdapter(strsql, conn)
        Dim ds As New DataSet()
        da.Fill(ds, "tbInfo")
        DataGridView1.DataSource = ds.Tables(0)
        conn.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

这是模块:

Sub connect()
    strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|datadirectory|\dbExam1.accdb"
    conn = New OleDbConnection(strcon)
    conn.Open()

    If conn.State = ConnectionState.Open Then
        MsgBox("CONNETED!")
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

您在哪里创建cmd变量?没有必要,因为您使用DataAdapater。

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    connect() 
    Try
    strsql = "select * from tbInfo"
    'comment this line   
    'cmd.CommandText = strsql 
    Dim da As New OleDbDataAdapter(strsql, conn) 
    Dim ds As New DataSet() 
    da.Fill(ds, "tbInfo") 
    DataGridView1.DataSource = ds.Tables(0) 
    conn.Close() 
    Catch ex As Exception 
    MsgBox(ex.Message) 
    End Try
    End Sub

    Sub connect() 
    strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|datadirectory|\dbExam1.accdb" 
    conn = New OleDbConnection(strcon) 
    conn.Open()

        If conn.State = ConnectionState.Open Then
            MsgBox("CONNETED!")
        End If
    End Sub