Cloud S
Cloud S

Reputation: 15

GridView + Access Database

I'm trying to link Access database with GridView control.

Here's the question: One successful procedure to link database query.

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

What I wanted is to re-run query if the first run returns no value/result in another procedure.

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

then put result into listbox.

However, I got error of "The ConnectionString property has not been initialized." on da.Fill(dt) when running the second time. First time was successful.

OK I finally got mistake corrected. I gotta Dim cn As New OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0;" & "Data Source = C:\Class.mdb") again to use query instead of once for all queries.

Upvotes: 0

Views: 747

Answers (1)

Steve
Steve

Reputation: 216363

Create and dispose the connection in the same method

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

Upvotes: 1

Related Questions