When I add a row into a DataGrdiView i get “The connection was not closed. The connection's current state is open” - vb.net

I have a datagridview (unbound) which is populated from MS SQL Server database.
During the loop of reading information from DB and adding rows to the datagridview1 i get this message :“The connection was not closed. The connection's current state is open” .
' Here is the code
Private Sub ShowMSR_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim col As New CalendarColumn() With {.HeaderText = "ROS Date"}
DataGridView1.Columns.Insert(5, col)
Dim col_1 = New DataGridViewTextBoxColumn
col_1.Name = "Date"
DataGridView1.Columns(5).DefaultCellStyle.Format = "dd/MM/yyyy"
Dim strsqlcommand As String = "SELECT * FROM MSR Where MSR_ID='" & MSRID & "'"
Dim dr As SqlDataReader
Dim sqlcommand = New SqlCommand(strsqlcommand, Form1.SQL_conn)
Dim itemcode As String = ""
Dim Desc As String = " "
Dim qty As String = " "
Dim un As String = " "
Dim AC As String = ""
Dim comm As String = ""
Dim rdate As Date
strsqlcommand = "Select Item_Code, Quantity, Unit, Item_Description, AC_No, ROS_time, Coment_RO From ITEMS Where MSR_ID
= '" & MSRID & "'"
sqlcommand.CommandText = strsqlcommand
dr = sqlcommand.ExecuteReader()
While dr.Read()
itemcode = dr(0).ToString
qty = dr(1).ToString
un = dr(2).ToString
Desc = dr(3).ToString
AC = dr(4).ToString
If IsDBNull(dr(5)) Then
rdate = CDate("1990/1/1")
Else
rdate = CDate(dr(5))
End If
comm = dr(6).ToString
Dim row As String() = New String() {itemcode, qty, un, Desc, AC, rdate, comm}
Me.DataGridView1.Rows.Add(row) '<---Here occur the problem
End While
dr.Close()
If (Form1.SQL_conn.State = ConnectionState.Open) Then Form1.SQL_conn.Close()
Catch ex As Exception
' the exception is never triggered
MsgBox(ex.Message)
If (Form1.SQL_conn.State = ConnectionState.Open) Then Form1.SQL_conn.Close()
End Try
End Sub

Related

VB.NET ACCESS Database birhtday request X time

I have the following problem: I want to extract from my access database the concerts that took place on day X. (Anniversary principle). I wish to release a report from this result. (The state works fine on its own. When I call it from VB without modifying the where clause) I wanted to prepare, for example, 5 states in advance. So I wrote this code:
`{'Dim DateJour As String
Dim I As Integer = 1
Dim strDB As String = CheminBase & "JH.mdb"
Dim RptNom As String
For I = 1 To 5
DateJour = I
If DateJour < 10 Then DateJour = "0" & DateJour
Dim Mois As String = Month(Date.Today)
If Mois < 10 Then Mois = "0" & Mois
Dim Annee As String = Year(Date.Today)
DateJour = DateJour & Mois & Annee
ClauseWhere = "Format([con_date],ddmm) = Format(" & _ DateAdd(Interval:=DateInterval.Day, I, Date.Today) & ",ddmm) order by con_Date DESC "
RptNom = "FICHE_JOUR_CONCERT_PLAN"
OLEOpenReport_PLAN(strDB, RptNom, AcView.acViewPreview, , ClauseWhere)
Next
MsgBox("Planification terminée")`}`
Here is the code of OLEOpenReport_PLAN
`{Private Function OLEOpenReport_PLAN(ByVal strDBName As String, ByVal strRptName As String, Optional ByVal intDisplay As Access.AcView = Access.AcView.acViewNormal, Optional ByVal strFilter As String = "", Optional ByVal strWhere As String = "") As Boolean
Dim bReturn As Boolean = True
Try
Dim objAccess As New Access.Application
objAccess.OpenCurrentDatabase(strDBName, False)
objAccess.DoCmd.OpenReport(strRptName, intDisplay, strFilter, strWhere, _ Access.AcWindowMode.acWindowNormal)
objAccess.DoCmd.OutputTo(Access.AcOutputObjectType.acOutputReport, strRptName, _ OutputFormat:="PDF", "C:\Users\" & Environment.UserName & "\AppData\Roaming\IP-Informatique _ Pourrieres\J H L Appli\Editions\Editions Planifiees\" & strRptName & "_" & DateJour & _".pdf",,,,)
objAccess.Quit(Access.AcQuitOption.acQuitSaveNone)
objAccess = Nothing
Catch ex As Exception
bReturn = False
MessageBox.Show(ex.ToString, "Erreur Automation", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Try
Return bReturn
End Function}`
At runtime I receive an "Operator absent" error at the level of the clausewhere. I also tried:
'{'ClauseWhere = "Format([con_date],ddmm) = Format(Date()+" & 1 & ",ddmm) order by con_Date DESC "'}'
which gives me the same error.
To be complete, here is the code of the state request:
'SELECT CONCERTS.CON_Date, CITIES.VIL_NOM
FROM CITIES INNER JOIN CONCERTS ON CITIES.IDVILLE = CONCERTS.IDVILLE;
`
Thank you in advance for your help.
Thierry
Assuming dates are stored as Dates...
I only know the vb end of this. Using the the Day and Month functions of Access Sql compare these to the Day and Month of your desired ann. date to get the concerts on this date in any year.
Private Function GetAnniversaries(AnnDate As Date) As DataTable
Dim dt As New DataTable
Dim selectString = "SELECT CONCERTS.CON_Date, CITIES.VIL_NOM
FROM CITIES
INNER JOIN CONCERTS ON CITIES.IDVILLE = CONCERTS.IDVILLE
Where Day(CONCERTS.CON_Date) = #Day And Month(CONCERTS.CON_Date) = #Month;"
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(selectString, cn)
cmd.Parameters.Add("#Day", OleDbType.Integer).Value = Day(AnnDate)
cmd.Parameters.Add("#Month", OleDbType.Integer).Value = Month(AnnDate)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click() Handles Button1.Click
'To see what was returned
Dim AnniversaryDate = Now
Dim dt = GetAnniversaries(AnniversaryDate)
DataGridView1.DataSource = dt
End Sub

how to insert a multiple data in datagrid using vb.net from sql

This is my code is for adding data in datagridview -
Dim rdr1 As MySqlDataReader
If Trim(txteventname.Text) = "" Or Trim(cbomenulist.Text) = "" Or Trim(cbopax.Text) = "" Or txteventname.Text = "" Or cbomenulist.Text = "" Or cbopax.Text = "" Then
MsgBox("Invalid Input of Data", vbInformation, "Validation")
Else
Dim strSql As String
Call myconnection()
Con.Open()
strSql = "SELECT p.product_no,p.product_name, p.product_pcs, p.product_price,d.menu_no FROM tblmenu as p,tblmenu_details as d where p.menu_no=d.menu_no and d.menu_name like '" & cbomenulist.Text & "%'"
Dim cmd11 As New MySqlCommand(strSql, Con)
rdr1 = cmd11.ExecuteReader
If rdr1.Read Then
Dim productno As New DataGridViewColumn
Dim productname As New DataGridViewColumn
Dim quantity As New DataGridViewColumn
Dim productprice As New DataGridViewColumn
Dim productmenu As New DataGridViewColumn
productno = rdr1("product_no")
productname = rdr1("product_name")
quantity = rdr1("product_pcs")
productprice = rdr1("product_price")
productmenu = rdr1("menu_no")
dtgproducts.Columns.Add(productno).ToString()
dtgproducts.Columns.Add(productname).ToString()
dtgproducts.Columns.Add(quantity).ToString()
dtgproducts.Columns.Add(productprice).ToString()
dtgproducts.Columns.Add(productmenu).ToString()
For i As Integer = 0 To dtgproducts.Rows.Count - 1 Step +1
Dim rowsa As Boolean = False
If rdr1.Read Then
Dim row As DataGridViewRow = dtgproducts.Rows(i)
If dtgproducts.Rows.Count = 0 Then
For j As Integer = 0 To dtgproducts.Rows.Count Step +1
If row.Cells(0).Value.ToString() = dtgproducts.Rows(j).Cells(0).Value.ToString Then
rowsa = True
End If
Next
If rowsa = False Then
dtgproducts.Rows.Add(row.Cells(0).Value.ToString)
dtgproducts.Rows(dtgproducts.Rows.Count - 1).Cells(0).Value = rdr1("product_no")
dtgproducts.Rows(dtgproducts.Rows.Count - 1).Cells(1).Value = rdr1("product_name")
dtgproducts.Rows(dtgproducts.Rows.Count - 1).Cells(2).Value = rdr1("product_pcs")
dtgproducts.Rows(dtgproducts.Rows.Count - 1).Cells(3).Value = rdr1("product_price")
dtgproducts.Rows(dtgproducts.Rows.Count - 1).Cells(4).Value = rdr1("menu_no")
End If
End If
'dtb = dtgproducts.Rows(i).Cells(3)
End If
Next
End If
End If
Con.Close()
Here, all the data that is listed in the database as a point of sale style of inserting a data, but this multiple data that I inserted in datagridview.
I want to insert multiple data in datagrid. How can I do that with this code?

how to update specific cell in data grid view using SQL and VB.net

I am trying to update a specific cell in datagridview using vb.net and sql ( or any other method)
I am using this code to split somme strings and save it into database.
Private Sub SalveazaData()
Dim list As String() = rtbComData.Text.Split(Environment.NewLine.ToCharArray())
SmdDataDataSet1.SearchAdrese.Rows.Clear()
SmdTableTableAdapter.ClearSearchAdrese()
Me.SearchAdreseTableAdapter.Update(Me.SmdDataDataSet1.SearchAdrese)
For Each Row As String In list
If Not (Row = "AT+DSCAN" Or Row = "OK" Or Row = "" Or Row = "AT+RSSI") Then
Dim s As String() = Split(Row, "|")
Dim aRow As smdDataDataSet1.smdTableRow = SmdDataDataSet1.smdTable.NewsmdTableRow()
aRow.Model = s(0)
aRow.AdresaUnica = s(1)
aRow.StatusModul = "ACTIVE"
Try
SmdDataDataSet1.SearchAdrese.Rows.Add(s(1))
SmdDataDataSet1.smdTable.Rows.Add(aRow)
Catch ex As Exception
Dim u As String
u = SmdTableTableAdapter.UpdateInactivActiv()
End Try
End If
Next
'selectzr()
salveaza()
status()
DataGridView1.Refresh()
End Sub
The table has the columns
Model | Adresa Unica | Status | time | InstAddress |
ZR 123456 active
ZR 654321 active
What i want to do is update the row with the address "123456" or "654321" and write in their specific cell , in this case the cell from the column | time | a value .
Can you please help me .?
I have made some digging and i have fund an answer.
please see below the code i've used in my application
Private Sub GroupCommandRtime()
Dim list As String() = rtbComData.Text.Split(Environment.NewLine.ToCharArray())`enter code here`
Dim ListaAdrese As List(Of String) = GetAdreseID()
For Each Row As String In list
For Each _Adresa As String In ListaAdrese
If Not (Row = "at+remote=" Or Row = "AT+RSSI" Or Row = "OK") Then
Try
Dim s As String() = Split(Row, " ")
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database\smdData.mdf;Integrated Security=True;User Instance=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE smdTable SET datetime='" + s(3) + "' WHERE AdresaUnica = '" + s(0) + "'"
cmd.ExecuteNonQuery()
Me.SmdTableTableAdapter.Fill(Me.SmdDataDataSet1.smdTable)
DataGridView1.Refresh()
Catch ex As Exception
End Try
End If
Next
Next
End Sub

How to change value of /GrpPwd/ Cell in all Rows?

I need to perform this SQL Query:
UPDATE Resurses SET GrpPwd = #GrpPwd1 WHERE Resurs = #Resurs1
For all rows in my Access Database using VB.NET
How can i do it?
I use this code but id doesn't work:
Password Generator:
Dim charset As String = nalf
Dim r As New Random()
Dim lenPass As Integer = r.Next(minLength, maxLength)
Dim str As String = String.Empty
For i As Integer = 0 To lenPass - 1
str += charset(r.Next(0, charset.Length))
Next
Return str
End Function
Update rows
If DataGridView1.CurrentRow.Cells(3).Value = "Yes" Then
nres = DataGridView1.CurrentRow.Cells(0).Value
nalf = DataGridView1.CurrentRow.Cells(6).Value
nsym = DataGridView1.CurrentRow.Cells(1).Value
Dim parol1 As String
Dim pwd As String = pass99(nsym, nsym) '
parol1 = pwd
Dim cmd As New OleDbCommand()
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.oledb.12.0; Data source=" + bpath)
cmd.Connection = Conn
Conn.Open()
For i As Integer = 0 To k - 1
cmd.CommandText = String.Format("UPDATE Resurses SET GrpPwd = #GrpPwd1{0} WHERE Resurs = #Resurs1{0};", i)
cmd.Parameters.Add(String.Format("#GrpPwd1{0}", i), OleDbType.WChar).Value = parol1
cmd.Parameters.Add(String.Format("#Resurs1{0}", i), OleDbType.Integer).Value = nres
Next
cmd.ExecuteNonQuery()
Conn.Close()
MsgBox("All rows are updated!")
End If
f

multiple SQL queries stored as vb.net variable

I know there are a few other posts about putting sql results into a vb.net variable but I just couldn't wrap my head around how they did it and how I could do it in my project.
So what I'm trying to do is query my database for 4 different values and then display each value in a certain part of the form. I was going to store the each value into a variable and then do an textbox1.text = i
Updated code for 10/5/2014
Private Sub LBmembers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
Dim i As String = LBmembers.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime, WorkPercent, Share FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = i
Using reader = cmd.ExecuteReader()
If reader.Read() Then
TBtimestart.Text = reader.ToString(0)
TBtimeend.Text = reader.ToString(1)
Dim j = Convert.ToInt32(reader.ToString(2))
TBtimecycle.Text = reader.GetInt32(3).ToString
TBmemberpercent.Text = reader.GetInt32(4)
TBmembershare.Text = reader.GetInt32(5)
If j = 1 Then
RBpro.Checked = True
ElseIf j = 2 Then
RBret.Checked = True
ElseIf j = 3 Then
RBcov.Checked = True
ElseIf j = 4 Then
RBskiff.Checked = True
ElseIf j = 5 Then
RBmack.Checked = True
ElseIf j = 6 Then
RBhulk.Checked = True
Else
RBpro.Checked = False
RBret.Checked = False
RBcov.Checked = False
RBskiff.Checked = False
RBmack.Checked = False
RBhulk.Checked = False
Exit Sub
End If
End If
End Using
con.Close()
End Using
End Using
End Sub
The exception
InvalidCastException was unhandled Specified cast is not valid.
Pops up on the line TBtimecycle.text = reader.GetInt32(3).ToString
The reader is also reading "System.Data.OleDb.OleDbDataReader" when I insert the test code "TBgrossisk.Text = reader.ToString()" into the using statement
If you look carefully to the syntax of the SELECT statement you will see that you can request any column of the table with just one query.
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
if string.IsNullOrWitheSpace(ListBox1.SelectedItem.ToString()) Then
MessageBox.Show("Select an item from the Listbox")
End If
Dim member As String = ListBox1.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime " & _
"FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = member
Using reader = cmd.ExecuteReader
if reader.Read() Then
TextBox1.Text = reader.GetString(0)
TextBox2.Text = reader.GetString(1)
Dim j = reader.GetInt32(2)
If j = 1 Then
Radio1.Checked = True
ElseIf j = 2 Then
Radio2.Checked = True
ElseIf j = 3 Then
Radio3.Checked = True
ElseIf j = 4 Then
Radio4.Checked = True
ElseIf j = 5 Then
Radio5.Checked = True
ElseIf j = 6 Then
Radio6.Checked = True
Else
Exit Sub
End If
TextBox4.Text = reader.GetInt32(3).ToString()
Else
MessageBox.Show("The search for '" & member & "' doesn't find any data")
End If
End Using
End Using
End Using
End Sub
Instead of using ExecuteScalar that returns just the first column of the first row retrieved you could use an OleDbDataReader returned by the method ExecuteReader. This object allows to access the various column in the current record using an index (or the column name). Read more about OleDbDataReader in MSDN