Vb.net没有将访问数据库加载到datagridview中

时间:2018-03-26 17:23:17

标签: vb.net

我无法理解为什么我的Access数据库不会为我加载到DataGridView中。我的代码中没有错误,所以我不确定发生了什么。我唯一得到的错误是未声明配置元素。

Imports System.Data.OleDb

Public Class Form1
Dim conn As New OleDbConnection

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim objConn As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = Students.accdb"
    conn.Open()

    dataGridShow()

End Sub

Private Sub dataGridShow()
    Dim objDS As New DataSet
    Dim objDT As New DataTable
    objDS.Tables.Add(objDT)

    Dim objDA As New OleDb.OleDbDataAdapter
    objDA = New OleDbDataAdapter("SELECT * FROM Students", conn)
    objDA.Fill(objDT)

    DataGridView1.DataSource = objDT.DefaultView

    conn.Close()

End Sub

End Class

我的应用配置如下所示。我的数据库位于bin / Debug

<?xml version="1.0" encoding="utf-8"?
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <connectionStrings>
  </connectionStrings>
</configuration>

1 个答案:

答案 0 :(得分:0)

您无需打开和关闭连接。 DataAdapter为您做到了这一点。如果没有有效的连接字符串,您的连接将无法工作,因此我将连接字符串移动到dataGridShow过程并设置conn对象的ConnectionString属性。

Private conn As New OleDbConnection

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        dataGridShow()
    End Sub

    Private Sub dataGridShow()
        Dim objDS As New DataSet
        Dim objDT As New DataTable
        objDS.Tables.Add(objDT)
        Dim objConn As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = Students.accdb"
        conn.ConnectionString = objConn
        Dim objDA As New OleDb.OleDbDataAdapter("SELECT * FROM Students", conn)
        objDA.Fill(objDT)
        DataGridView1.DataSource = objDT.DefaultView
    End Sub