Syaza Nazurah
Syaza Nazurah

Reputation: 1

The connection was not closed the connection current state is open

Hye... I currently doing my final year project using vb.net and i got this error. Im tryin' to fix the error but still not succeed. I use ms access for database in my project. I try to put con.Open() before the 'dt' statement and con.Close() after the 'cboProduct.Select' but the result is the same. Really appreciate your helps. Thanks :)

'GLOBAL DECLARATIONS
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Acer User\Documents\MAKLUMAT IVENTORI.accdb"
Dim con As OleDbConnection = New OleDbConnection(conString)
Dim adapter As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim ds As New DataSet

Private Sub RefreshData()
    dt = New DataTable
    ds = New DataSet
    ds.Tables.Add(dt)

    adapter = New OleDbDataAdapter("Select * FROM product WHERE lab_kod='66'", con)
    adapter.Fill(dt)
    DataGridView1.DataSource = dt.DefaultView

    labelID.Text = getAutoID()
    lblLabCode.Text = "66"
    cboProduct.Select()

    Dim v_SQL As String = "SELECT * FROM kategori_product"
    cmd = New OleDbCommand(v_SQL, con)
    con.Open()

    Dim v_dataReader As OleDbDataReader = cmd.ExecuteReader()
    Dim v_dataTable As New DataTable
    v_dataTable.Columns.Add("product_kod", Type.GetType("System.String"))

    If v_dataReader.HasRows Then
        While v_dataReader.Read
            v_dataTable.Rows.Add(v_dataReader.GetString(0))
        End While
        cboProduct.DataSource = v_dataTable
    End If

    cboProduct.DisplayMember = "product_kod"
    cboProduct.ValueMember = "product_kod"
    v_dataReader.Close()
    con.Close()
End Sub

Upvotes: 0

Views: 292

Answers (1)

Dai
Dai

Reputation: 155558

  1. Don't store short-lived objects, such as database connections, as global variables.
  2. In fact, don't use global variables, ever, at all.
    (though I note that assuming this is a Class and not a Module those are actually class fields, not globals, but you're still misusing them)
  3. Your OleDbDataAdapter.Fill call requires the connection to be open, but you call .Fill(dt) before calling con.Open()
  4. Use Using (using() in C#) blocks to ensure your database connection is always closed, even in the event of failure.

Upvotes: 1

Related Questions