VB.net Load(cmd.ExecuteReader) - vb.net

I have a function which i am getting syntax Error which I am using the same copy in other without any error .I am trying to open an Access table and read line by line and do some updates on it .
Function FlattenTable(Current As String, Freezefrom As Date, DateRef As Date, db As String)
Dim date1 As Date
Dim sql1 As String
Dim FreezeHrs As Double
Dim FreezeLnds As Long
Dim rs1 As DataTable
Dim cmd As OleDb.OleDbCommand
Dim con As New OleDb.OleDbConnection With {
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & db
}
con.Open()
If Freezefrom > DateRef Then
date1 = Freezefrom
Else
date1 = DateRef
End If
sql1 = "SELECT * FROM [Hours & Landings & Cycles] WHERE [A/C] = '" & Current & "' [DATE]= " & date1 & ""
cmd = New OleDbCommand(sql1, con)
rs1 = New DataTable
rs1.Load(cmd.ExecuteReader)
FreezeHrs = rs1.Rows.Item(0).Item(3)
FreezeLnds = rs1.Rows.Item(0).Item(4)
' "UPDATE [Hours & Landings & Cycles] SET [Code] = 'X' WHERE [A/C] = '" & Current & "' AND [Date]>=" & ActualEIS & " AND [Date]<=#" & DateValue(Format("{0:MM/dd/yyyy}", EndDate)) & "#"
sql1 = "UPDATE [Hours & Landings & Cycles] SET [HRS] = '" & FreezeHrs & "' WHERE [A/C] = '" & Current & "' AND [DATE]>='" & date1 & "'"
cmd = New OleDbCommand(sql1, con)
cmd.ExecuteNonQuery()
End Function
rs1.Load(cmd.ExecuteReader) is a data table reader

Related

Searching multiple tables in Access vb.net

I have a search button which looks up for data only in tblDopage but there is a field strMatrice in this table that is linked to table tblMatrice. So if the user is searching for Matrice I should retrieve Matrice from tblMatrice and innerjoin it with tblDopage on strMatrice, it's like a search inside search and the result of searching for matrice is more than 1 result so that I have many results which i should link them with tblDopage to display the final result. What shall i do, I spended 3 days searching for a solution.
I retrieved strMatrice from tblMatrice and populated a dataset with the result but I don't know how to innerjoin between a dataset and table in the database which is the tblDopage
Help is very appreciated, Thank you in advance
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim sql = "SELECT * from tblDopages WHERE "
cmd = New OleDbCommand(Sql, myConnection)
Dim da As OleDbDataAdapter
If CKBrefech.Checked = True Then
sql = sql & "strRefEch = '" & TBrefech.Text & "' AND "
End If
If CKBmethode.Checked = True Then
sql = sql & "strMethode = '" & CBmethode.Text & "' AND "
End If
If CKBpurif.Checked Then
sql = sql & "strPurif = '" & CBpurif.Text & "' AND "
End If
If CKBmatrice.Checked Then
sql = sql & "strMatrice = '" & CBmatrice.Text & "' AND "
End If
If CKBmol.Checked Then
sql = sql & "strMolecule = '" & CBmol.Text & "' AND "
End If
If CKBechprep.Checked Then
sql = sql & "datDatePrepa >= #DatPrepa AND "
cmd.Parameters.Add("#DatPrepa", OleDbType.Date).Value = DTPechprep.Value.Date
End If
If CKBechau.Checked Then
sql = sql & "datDatePrepa <= #Datau AND "
cmd.Parameters.Add("#Datau", OleDbType.Date).Value = DTPechau.Value.Date
End If
If CKBtrigprepa.Checked = True Then
sql = sql & "strTrigPrepa = '" & TBtrigprepa.Text & "' AND "
End If
If CKBtriganaly.Checked = True Then
sql = sql & "strTrigAnaly = '" & TBtrigAnaly.Text & "' AND "
End If
If CKBappar.Checked = True Then
sql = sql & "strNomTech = '" & CBappar.Text & "' AND "
End If
If CKBnumappar.Checked = True Then
sql = sql & "[strEquip(Appareil)] = '" & CBnumappar.Text & "' AND "
End If
If CKBteneurmini.Checked = True Then
sql = sql & "dblDopage >= " & TBteneurmini.Text & " AND "
End If
If CKBteneurmax.Checked = True Then
sql = sql & "dblDopage <= " & TBteneurmax.Text & " AND "
End If
'if referentiel is enabled
myConnection.Close()
If CKBnomref.Checked Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'Get IDref from table tblRefMatDetails and then make an innerjoin with tblRefMatrice to retrieve the matrice and insert it into the search query of tblDopages
Dim query = "select distinct a.strMatrice from tblRefMatrice a INNER JOIN tblRefMatDetails b on a.intIDref=b.intIDRef where "
cmd = New OleDbCommand(query, myConnection)
Try
If CKBnomref.Checked Then
query = query & "b.strReferentiel = '" & CBnomref.Text & "' AND "
End If
If CKBniv1.Checked Then
query = query & "b.strNIveau1 = '" & CBniv1.Text & "' AND "
End If
If CKBniv2.Checked Then
query = query & "b.strNiveau2 = '" & CBniv2.Text & "' AND "
End If
If CKBniv3.Checked Then
query = query & "b.strNiveau3 = '" & CBniv3.Text & "' AND "
End If
If CKBniv4.Checked Then
query = query & "b.strNiveau4 = '" & CBniv4.Text & "' AND "
End If
' Remove the last AND if any ....'
If query.EndsWith(" AND ") Then
query = query.Substring(0, query.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If query.EndsWith(" WHERE ") Then
query = query.Substring(0, query.Length - 7)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
cmd.CommandText = query
cmd.Connection = myConnection
Dim MyDataTable As New DataTable
Dim da As New OleDbDataAdapter(query, myConnection)
da.Fill(MyDataTable)
Dim row As DataRow
For Each row In MyDataTable.Rows
Dim strMatrice As String
strMatrice = row("strMatrice")
Next row
DataGridView2.DataSource = MyDataTable
'to focus on first row of DGV after populating it
DataGridView2.Rows(0).Selected = True
myConnection.Close()
Dim matrice As String
For x As Integer = 0 To DataGridView2.Rows.Count - 2
matrice = DataGridView2.Rows(x).Cells(0).Value
sql = sql & " strMatrice = '" & matrice.ToString & "' AND "
Dim row As DataRow
For Each row As DataRow In MyDataTable.Rows
matrice = row.Item("Detail")
Next row
Next
End If
' Remove the last AND if any ....'
If sql.EndsWith(" AND ") Then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If sql.EndsWith(" WHERE ") Then
sql = sql.Substring(0, sql.Length - 7)
End If
' cmd = New OleDbCommand(sql, myConnection)
cmd.CommandText = sql
cmd.Connection = myConnection
Dim MyDataSet As New DataSet
da = New OleDbDataAdapter(sql, myConnection)
da.SelectCommand = cmd
da.SelectCommand.Parameters.Add(New OleDbParameter("#DatPrepa", DTPechprep.Value)) 'adding date parameters to datatable
da.SelectCommand.Parameters.Add(New OleDbParameter("#datau", DTPechprep.Value)) 'adding date parameters to datatable
'da.SelectCommand.Parameters.Add(New OleDbParameter("#Matrice", matrice.ToString)) 'adding Matrice parameters to datatable
da.Fill(MyDataSet, "Matrice")
DataGridView1.DataSource = MyDataSet.Tables("Matrice")
'to focus on first row of DGV after populating it
DataGridView1.Rows(0).Selected = True
LBnumresult.Text = DataGridView1.RowCount - 1

An expression of non-boolean type specified in a context where a condition is expected, near 'and'

I have converted my database from Access to Sql as Sql didn't accept format() so is displaying an error.
This is my code:
DefaultStr = "" &
"SELECT StudentAccount.Dated, StudentAccountS.StAdmNo, StudentAccountS.StClass, " &
"StudentAccountS.StName, StudentAccount.Perticular, StudentAccount.Amount,StudentAccount.Remark,StudentAccount.PayMode,TransactionID " &
"FROM (StudentAccount LEFT OUTER JOIN StudentAccountS ON StudentAccount.SSID = StudentAccountS.SSID) " &
"WHERE (StudentAccount.Debit) and (StudentAccount.Dated Between " &
"#" & Format(DateFrom, "MM/dd/yyyy") & "# AND #" & Format(DateTo, "MM/dd/yyyy") & "#)"
Select Case SIndex
Case 0
SelStr = " AND (StudentAccount.PayMode = '" & OptionStr & "') Order By StudentAccount.Dated"
Case 1
SelStr = " AND (StudentAccount.Perticular = '" & OptionStr & "') Order By StudentAccount.Dated"
Case 2, 3
SelStr = " AND (StudentAccount.TransType = '" & filterStr & "') Order By StudentAccount.Dated"
Case Else
SelStr = Nothing
End Select
Da = New SqlDataAdapter(DefaultStr & SelStr, Conn)
Ds = New DataSet
Da.Fill(Ds)
You have to use something like this:
Dim CMD As SqlClient.SqlCommand = Conn.CreateCommand
Dim dtStart As DateTime = New DateTime(2015, 9, 6, 10, 1, 0)
Dim dtEnd As DateTime = New DateTime(2015, 9, 6, 11, 0, 0)
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN '" & dtStart.ToString("yyyy-MM-dd HH:mm:ss") & "' AND '" & _
dtEnd.ToString("yyyy-MM-dd HH:mm:ss") & "'"
Dim DA As New SqlClient.SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
Howewer i suggest you to start learing SqlParameter for queries (that are much more reliable, as for example in dealing with sql injection). Simply use something like that:
CMD.Parameters.Add("#DateStart", SqlDbType.DateTime2, 20).Value = dtStart
CMD.Parameters.Add("#DateEnd", SqlDbType.DateTime2, 20).Value = dtEnd
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN #DateStart AND #DateEnd"

Select query based on date format in access using vb.net

I want to fetch data from a database that falls between two dates.
The code:
con1.Open()
Dim re As String = ""
Dim d1 As DateTime = DateTimePicker2.Value.ToString("dd/MM/yyyy")
Dim d2 As DateTime = DateTimePicker3.Value.ToString("dd/MM/yyyy")
Dim cmd As New OleDbCommand("Select lno,pname,mdue,ramt from Due where ddate >= '" + Convert.ToDateTime(d1) + "' and ddate<= '" + Convert.ToDateTime(d2) + "' and ramt='0'", con1)
Dim da As OleDbDataReader = cmd.ExecuteReader
While (da.Read())
re = re & " " & da("lno").ToString.PadRight(30) & " " & da("pname").ToString.PadLeft(10) & " " & da("mdue").ToString.PadLeft(10) & Chr(13)
End While
I get a data type mismatch error. The datatype for date is Date/Time only.
You are converting to string before assiging to your DateTime variables!
Try
con1.Open()
Dim re As String = ""
Dim d1 As DateTime = DateTimePicker2.Value
Dim d2 As DateTime = DateTimePicker3.Value
Dim cmd As New OleDbCommand("Select lno,pname,mdue,ramt from Due where ddate >= #" & String.Format("{0:dd/MM/yyyy}", d1) & "# and ddate<= #" & String.Format("{0:dd/MM/yyyy}", d2) & "# and ramt='0'", con1)
Dim da As OleDbDataReader = cmd.ExecuteReader
While (da.Read())
re = re & " " & da("lno").ToString.PadRight(30) & " " & da("pname").ToString.PadLeft(10) & " " & da("mdue").ToString.PadLeft(10) & Chr(13)
End While
You should also probably use & as the concatenation operator ... https://msdn.microsoft.com/en-us/library/te2585xw.aspx

updating a sql 2005 database using text boxes in vb.net

I have a VB.Net form which allows the user to update the customer details such as name, contact no:, etc. So when the customer enters the new name for the customer name etc. the application should update the corresponding field in the existing entry that relates to the customer ID.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cn
cn.Open()
cmd.CommandText = " UPDATE TblCustomerDetails (compID, compName, compContact, compAddress, compFax, compEmail, compPayterm, compTaxscheme, compPaymode, compRemarks ) SET Values ('" & lblCID.Text & "', '" & txtCname.Text & "', '" & txtCpno.Text & "', '" & txtCaddrs.Text & "','" & txtCfax.Text & "', '" & txtCemail.Text & "', '" & cmbPterm.Text & "','" & cmbTaxschm.Text & "',' " & cmbPmode.Text & "', '" & txtRemarks.Text & "') WHERE compID = '" & lblCID.Text & "';"
cmd.ExecuteNonQuery()
MsgBox("Account updated!!", MsgBoxStyle.Information, "Updation complete")
Your using a INSERT syntax for your UPDATE statement. Your UPDATE statement should have the form:
UPDATE tableName
SET col1 = val1,
col2 = val2,
col3 = val3
WHERE someColumn = someValue
Additionally, you are wide open to SQL Injection attacks by using non-parameterized queries. Finally, I would use a Using blocks to ensure your connection and command are properly closed and disposed of.
Putting it all together it would look something like this:
Using Dim cn As SqlConnection = New SqlConnection("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cn.Open()
Dim sqlQuery As String = "UPDATE TblCustomerDetails " + _
"SET compName = #compName, " + _
"compContact = #compContact, " + _
"compAddress = #compAddress, " + _
"compFax = #compFax, " + _
"compEmail = #compEmail, " + _
"compPayterm = #compPayterm, " + _
"compTaxscheme = #compTaxscheme, " + _
"compPaymode = #compPaymode, " + _
"compRemarks = #compRemarks " + _
"WHERE compID = #compID"
Using Dim cmd As SqlCommand = New SqlCommand(sqlQuery, cn)
cmd.Parameters.AddWithValue("#compFax", txtCname.Text)
cmd.Parameters.AddWithValue("#compContact", txtCpno.Text)
cmd.Parameters.AddWithValue("#compAddress", txtCaddrs.Text)
cmd.Parameters.AddWithValue("#compFax", txtCfax.Text)
cmd.Parameters.AddWithValue("#compEmail", txtCemail.Text)
cmd.Parameters.AddWithValue("#compPayterm", cmbPTerm.Text)
cmd.Parameters.AddWithValue("#compTaxscheme", cmbTaxschm.Text)
cmd.Parameters.AddWithValue("#compPaymode", cmbPmode.Text)
cmd.Parameters.AddWithValue("#compRemarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#compID", lblCID.Text)
Dim result As Integer
result = cmd.ExecuteNonQuery()
If result = 1 Then
MsgBox("Account updated!!", MsgBoxStyle.Information, _
"Updation complete")
Else
MsgBox("Account not updated!!", MsgBoxStyle.Information, _
"Updation not complete")
End If
End Using
End Using
There are a few more things to note in the above code sample:
First, I removed compID from the list of values to update. You're using that in your WHERE query, so I think you would have interesting results in your query if you're trying to update the same column you are using as part of your WHERE clause. Additionally, the source for that value is a Label, which tells me it's not supposed to be changed.
Secondly, ExecuteNonQuery() returns an int with the number of rows affected. In this case, it should be 1 - if it's not 1, I have you show a different message box.
Thirdly, cmbPTerm, cmbTaxxshm and cmbPmode sound like ComboBox to me, and you're not going to get what I think you're expecting using their Text property. I think you'll want SelectedText - hard to say without knowning how your ComboBoxes are bound. I'll leave that as an exercise for you :)
Fourth, I broke the UPDATE query up across several lines simply for readability - you don't have to do it that way, as long as the query is correct.
Finally, I'd suggest using MessagBox.Show() vs MsgBox.
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand
cnn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "update TblCustomerDetails set compName='" & txtCname.Text & "' , compContact = '" & txtCpno.Text & "' , compAddress = '" & txtCaddrs.Text & "' , compFax = '" & txtCfax.Text & "' , compEmail = '" & txtCemail.Text & "' , compPayterm = '" & cmbPterm.Text & "' , compTaxscheme = '" & cmbTaxschm.Text & "' , compPaymode = '" & cmbPmode.Text & "' , compRemarks = '" & txtRemarks.Text & "' where compID = '" & lblCID.Text & "'"
cmd.ExecuteNonQuery()
cnn.Close()
MessageBox.Show("entry updated!!!")

how to refresh datagrid and update database?

i have some trobles in updating my database. ihave this codes :
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
cmd.ExecuteNonQuery()
DataGridView1.Refresh()
Finally
'reader.Close()
End Try
conn.Close()
my problem is, by these code, the grid can be refreshed after i close and open this form again. but if i check in my ms Access, the data was not chanded at all. how to update my database and showed in my datagrid??
Try This :
Dim cmd As OleDbCommand
Dim rstTable As New DataTable()
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
rstTable.Load(cmd.ExecuteReader())
DataGridView1.DataSource =rstTable
Finally
'reader.Close()
End Try
conn.Close()
your gridview columns should have bound to a field