The connection was not closed the connection current state is open - database

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

Don't store short-lived objects, such as database connections, as global variables.
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)
Your OleDbDataAdapter.Fill call requires the connection to be open, but you call .Fill(dt) before calling con.Open()
Use Using (using() in C#) blocks to ensure your database connection is always closed, even in the event of failure.

Related

Crystal Report not showing data from SQL Server 17.5

After creating a table and putting data in it in the previous form, this form tries to display the report, but I am getting a blank report. What am I doing wrong?
Here is my VB 2017 code for form load event:
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form5
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cryRpt As New ReportDocument
cryRpt.Load("C:\Users\Administrator\source\repos\WindowsApp3\WindowsApp3\CrystalReport4.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class
I solved my problem in the following way
Here is my modified VB 2017 code for form load event:
Dim query As String = "SELECT * FROM monAtt"
Dim cmd As New SqlCommand(query, conn1)
cmd.CommandType = CommandType.Text
conn1.Open()
Dim MyDA As New SqlClient.SqlDataAdapter()
MyDA.SelectCommand = cmd
Dim myDS As New TestDataSet1()
MyDA.Fill(myDS, "monAtt")
Dim oRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument()
oRpt.Load("C:\Users\Administrator\source\repos\WindowsApp3\WindowsApp3\CrystalReport4.rpt")
oRpt.SetDataSource(myDS.Tables("monAtt"))
CrystalReportViewer1.ReportSource = oRpt
CrystalReportViewer1.RefreshReport()
CrystalReportViewer1.Visible = True
conn1.Close()
cmd.Dispose()

Expiration Time out VB.Net

I'm turning an SQL Request in my application which is very big and need a lot of traitement. When I execute the request in SQL server, it takes time, but I have the result, but when I execute it in my application, after many seconds, it gives me an error of Time out Expiration.
Here is my VB.Net Button:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim str As String = "Data Source=----;Initial Catalog=----;Persist Security Info=True;User ID=---;Password=---"
Dim con As New SqlConnection(str)
Dim com As String = " ma RequĂȘte"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "Organisation")
DataGridView1.DataSource = ds.Tables(0)
End Sub
Can anyone help?

How to display data from SQL Server on a DataGridView

I want to load or show the data from SQL Server on a DataGridView.
The build succeeds and there's no error when I run it. There's nothing wrong in form modul_koneksi (I think) because it works on my other form (form_login)
However, nothing shows up in my DataGridView. How can I fix this?
Code:
Imports System.Data.SqlClient
Public Class FormProduk
Private Sub FormProduk_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
Dim connection As New SqlConnection(str)
Dim com As String = "Select * From tbl_user"
Dim dataadapter As New SqlDataAdapter(com, connection)
Dim dataset As New DataSet()
dataadapter.Fill(dataset, "tbl_user")
DataGridView1.DataSource = dataset.Tables()
End Sub
End Class
You should define which table to load in the DataGridView:
DataGridView1.DataSource = dataset.Tables("tbl_user")
You cannot set the .DataSource property with dataset.Tables. Instead you need to set it with a DataTable located in your DataSet:
DataGridView1.DataSource = dataset.Tables("tbl_user")
However I think you could simplify the code a little by getting rid of the SqlDataAdapter and loading straight into a DataTable
Dim dt As New DataTable
dt.Load(com.ExecuteReader())
DataGridView1.DataSource = dt
I would also consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
With the changes your code would look something like this:
Dim dt As New DataTable
Using con As New SqlConnection("Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"),
cmd As New SqlCommand("SELECT * FROM tbl_user", con)
con.Open()
dt.Load(cmd.ExecuteReader())
End Using
DataGridView1.DataSource = dt
Not enough info to tell, are you sure your connection string str is correct. You can try change to this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
Dim conn As New SqlConnection(str)
Dim cmd As String = "Select * From tbl_user"
Dim adapter As New SqlDataAdapter(cmd, conn)
Dim tabeluser As New DataSet
adapter.Fill(tabeluser)
DataGridView1.DataSource = tabeluser.Tables
End Sub

Datagridview vb won't work

I'm doing an A Level in computing (I'm terrible at programming so thats why im here) and I followed a tutorial to get a datagridview to load up a table in the database I have linked to the project and nothing comes up in the debug, still greyed out table.
Here is my code:
Imports System.Data.OleDb
Public Class Cards
Dim con As New OleDbConnection
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= |DataDirectory|\Cards.accdb"
con.Open()
datagridShow()
End Sub
Private Sub datagridShow()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("SELECT * FROM cards", con)
da.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
con.Close()
End Sub
End Class
'If there is no data in the Grid There are No Cells to click so your code won't trigger a DataGridView1.CellContentClick So you will never hit your DataGridView1_CellContentClick method
'I just ran your code and it worked. I did put my connection string in so check your connection 'string.
'I am not sure why you are loading the grid on the cell contact click.
'Try this and call loadData on pageload or a button click event this should work for you.
Private Sub loadData()
con.ConnectionString = "Your Connection String"
con.Open()
datagridShow()
End Sub
Private Sub datagridShow()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("SELECT * FROM cards", con)
da.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
con.Close()
End Sub

Loading data from SQL Server row by row to textboxes

I am trying to retrieve data row by row from my SQL Server and load them into my respective textboxes, I was doing the below code but of course it doesn't work as the For Each loop will load every single textboxes with each data retrieved, ran out of ideas. Appreciate if someone can give me a boost here. Thanks.
Private Sub retrieve_Data()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=HPEnvy-HP; Initial Catalog=Cinema; User Id=<id>; Password=<password>;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT [movie_ID], [movie_Title] FROM [Movie_Table] ORDER BY [MOVIE_ID] "
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim reader As String = lrd(1).ToString
Dim arrLoad As New ArrayList
arrLoad.Add(lrd(1).ToString)
For i = 0 To arrLoad.Count - 1
For Each cCtrl As Control In Panel1.Controls
If TypeOf cCtrl Is TextBox Then
Dim txtBox As New TextBox
txtBox = cCtrl
txtBox.Text = arrLoad.Item(i)
End If
Next
Next
End While
Catch ex As Exception
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
End Sub
you just "new" your textbox,
you didn't add your textbox to your form.
you should add some code like that:
this.Controls.Add(textbox);
or
this.Panel1.Controls.Add(textbox);

Resources