0

Access データベースを GridView コントロールにリンクしようとしています。

質問は次のとおりです。データベース クエリをリンクするための 1 つの成功した手順です。

Protected sub  Query(ByVal y as string)
    Dim da As New OleDbDataAdapter(y, cn)
    Dim dt As New DataTable()
    da.Fill(dt)
    da.Dispose()
    cn.Dispose()
    Me.GridView1.DataSource = dt
    Me.GridView1.DataBind()
    ListBox1.Visible = True
End sub

私が望んでいたのは、最初の実行で別の手順で値/結果が返されない場合にクエリを再実行することです。

Protected Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click    

x = "SELECT * From Class Where Gender ='Male' And First_name ='James' "
        Query(x)    
If gridview.rows.count =0 then
x= "SELECT * From Class Where Gender ='Male'"
       query(x)
    End If

結果をリストボックスに入れます。

しかし、2回目の実行時にエラーが発生しまし"The ConnectionString property has not been initialized." on da.Fill(dt)た。1回目は成功。

OK私はついに間違いを修正しました。Dim cn As New OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0;" & "Data Source = C:\Class.mdb") をもう一度使用して、すべてのクエリに対して一度ではなくクエリを使用する必要があります。

4

1 に答える 1

1

同じメソッドで接続を作成して破棄する

Protected Sub Query(ByVal y as string)     
  Dim dt As New DataTable()
  Using cn as New OleDbConnection("your_connection_string"), _
        da As New OleDbDataAdapter(y, cn)       
      da.Fill(dt)     
  End Using
  Me.GridView1.DataSource = dt     
  Me.GridView1.DataBind()     
End Sub
于 2012-05-29T12:16:26.557 に答える