ConnectionString 属性 尚未初始化错误 VB.NET

The ConnectionString property has not been initialized error with VB.NET

我正在尝试用来自访问的数据填充数据网格,但每次我 运行 这个程序时,我都会收到一条错误消息,说 ConnectionString property has not been initialized 我已经尝试了我所知道的一切。有人可以帮忙吗

 Private Sub RefreshData()
    cnn = New OleDb.OleDbConnection
    cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\My_db.accdb"
    If Not cnn.State = ConnectionState.Open Then
        ' open connection '
        cnn.Open()
    End If
    Dim da As New OleDb.OleDbDataAdapter()
    Dim dt As New DataTable

    'fill datatable'
    da.Fill(dt)

    Me.DataGridView1.DataSource = dt
    ' close connection'

    cnn.Close()
End Sub
Private Sub BindGrid()
    If Not cnn.State = ConnectionState.Open Then
        ' open connection '
        cnn.Open()
    End If
    Dim cmd As New OleDb.OleDbCommand
    cmd.Connection = cnn
    cmd.CommandText = "SELECT * FROM Training log WHERE Runner Name='" & Profile.UsernameTextBox.Text & "'"
    cmd.ExecuteNonQuery()

    Me.RefreshData()

    cnn.Close()
End Sub

似乎从未将 OleDbCommand 设置为使用 OleDbConnection 对象,并且从未将 DataAdapter 设置为使用该命令。试试这个,它还修复了其他几个不符合普遍接受的做法的项目:

'Put this module in a separate file
'Any and *ALL* code that talks directly to the DB should go in this module, and use the style of the RefreshData() method below.
Public Module DataLayer
    Private Property ConnectionString() As String
       Get
          Return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\My_db.accdb"
       End Get
    End Property

    'I left the name alone so you could match it up to your original code,
    ' but a better name would be something like "TrainingLogByRunner()"
    Public Function RefreshData(ByVal RunnerName As String) As DataTable
        Dim dt As New DataTable
        Using cnn As New OleDb.OleDbConnection(ConnectionString), _
              cmd As New OleDb.OleDbCommand("SELECT * FROM [Training log] WHERE [Runner Name]= ?", cnn), _
              da As new OleDb.OleDbDataAdapter(cmd)

            '**NEVER** use string concatentation to substitute this kind of value into a query!
            'Had to guess at column type/length here
            cmd.Parameters.Add("?", OleDbType.VarWChar, 40).Value = RunnerName

            'No need to call Open() for the connection...
            ' the DataAdapter.Fill() method will manage opening/closing the connection
            da.Fill(dt)
        End Using 
        Return dt
    End Function
End Module

Private Sub BindGrid()
    Me.DataGridView1.DataSource = DataLayer.RefreshData(Profile.UsernameTextBox.Text)
End Sub