Jeremy
Jeremy

Reputation: 21

how to open database connection in 1 form then close it in another form?

Public Class Login
Private Shared con As New OleDb.OleDbConnection
Dim sql As String
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text <> "[email protected]" Or TextBox2.Text <> "fcf1234567" Then
        MsgBox("Wrong username or password!! Please try again!!", 0, "!!!")
    Else
        con.Open()
        sql = "SELECT * FROM c_info"
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "c_information")
        Me.Hide()
        Home.Label6.Show()
        Home.Label6.Text = ds.Tables("c_information").Rows(0).Item(0)
        Home.Button8.Show()
        Home.Button6.Hide()
        Home.Button9.Show()
        Profile.Enabled = True
        Profile.TextBox1.Text = ds.Tables("c_information").Rows(0).Item(0)
        Profile.TextBox2.Text = ds.Tables("c_information").Rows(0).Item(1)
        Profile.TextBox3.Text = ds.Tables("c_information").Rows(0).Item(2)
        Profile.TextBox4.Text = ds.Tables("c_information").Rows(0).Item(3)
        Profile.TextBox5.Text = ds.Tables("c_information").Rows(0).Item(4)
        Profile.ComboBox1.Text = ds.Tables("c_information").Rows(0).Item(5)
    End If
End Sub

I'm doing a log-in system, try to open database connection then close it in another form, no idea how to do it...in this code i have typed con.open(), but when i run it twice, it says "current connection still open"

Upvotes: 0

Views: 773

Answers (1)

Josh Part
Josh Part

Reputation: 2164

3 Suggestions:

  1. (Less recomendable) Change con to Public Shared or Protected Shared (preferable to have it on a separate class/module); this way you'll be able to access it from all your forms and clases
  2. (Most adecuate to your scenario) Add a property on your 2nd form of OleDb.OleDbConnection or a parameter on its constructor and pass it from Form1 when you create the second form.
  3. (Most recommended) Rethink your design and logic. Having an open database connection wandering over all your program is a bad idea for many reasons. Create a database connection on every form/class you need one, open and close it as soon as you use it.

Upvotes: 1

Related Questions