Private Sub Button73_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button73.Click
Dim serienaam
Dim oud
Dim aantal As Integer
Dim tt
Dim bedrag As Integer
Dim totaal As Integer
serienaam = ComboBox1.SelectedItem
oud = ComboBox2.SelectedItem
aantal = TextBox7.Text
tt = "" & serienaam & " " & oud & " " & aantal & " "
cmd = New SqlCommand("SELECT '" & oud & "' FROM series Where naamserie = '" & serienaam & "' ", con)
Dim sdr As SqlDataReader = cmd.ExecuteReader()
If sdr.Read = True Then
Dim week = sdr.Item(" '" & oud & "' ") '\\gives a IndexOutOfRangeException...
bedrag = week
totaal = totaal + bedrag * aantal
sdr.Close()
'Label14.Text = totaal
ListBox1.Items.Add(tt)
End If
End Sub
When I run this it gives a IndexOutOfRangeException on
If sdr.Read = True Then
Dim week = sdr.Item(" '" & oud & "' ") \|/<---\|/gives a IndexOutOfRangeException...
bedrag = week
totaal = totaal + bedrag * aantal
Right, I'll try to answer this in an understandable fashion.
The main issue is your SQL query.
New SqlCommand("SELECT '" & oud & "' FROM series ...
What your query will look like is this. Oud will in this example be "ID":
SELECT 'ID' FROM series...
What you are telling the database is this:
For each row you can find send back the string 'ID'.
What you really want is this, notice the lack of apostrophes:
SELECT ID FROM series...
This will return the value in the Column named ID.
Run this query in this link and you'll understand better: http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
SELECT 'CustomerID', CustomerID FROM Customers;
As a bonus, code that I believe will work. Just put it in the same place as before.
Dim oud as String
oud = ComboBox2.SelectedItem.ToString()
cmd = New SqlCommand("SELECT " & oud & " FROM series Where naamserie = '" & serienaam & "' ", con)
Dim week = sdr.Item(oud) 'As rinukkusu said
I don't think you need to quote the column name at:
Dim week = sdr.Item(oud)
Related
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
Hope you can help - I'm having issues getting the last ID after INSERT.
So the environment - Access 2016, SQL Server and VBA
Dim db As DAO.Database
Dim RS As New ADODB.Recordset
Dim sql As String
I have theses declared and then private sub.
Private Sub CreateOrderHeader()
Dim CustomerID As Integer
Dim OrderDate As String
Dim OrderStatus As String
Dim OrderValue As Double
Dim OrderNotes As String
Dim OrderPostageID As String
Dim OrderAddressID As String
Dim OrderBatchID As Integer
Dim OrderPayment As String
Dim OrderCourierID As String
Dim OrderAgentID As Integer
Dim OrderOutstanding As Double
CustomerID = tbxCusID
OrderDate = Format(Now)
OrderStatus = "InProcess"
OrderValue = txtTotal.value
OrderNotes = tbxNotes.value
OrderPostageID = txtPostage.Column(0)
If tbxCustomerAddress = tbxDeliveryAddress Then
OrderAddressID = 3 'default customers address
Else
'NEED TO GET CUSTOMER ADDRESS TO DO
End If
OrderBatchID = cmbBatch.Column(0)
OrderPayment = sPayMethod
OrderCourierID = cbxShipping.Column(0)
OrderAgentID = 0
OrderOutstanding = txtTotal.value
Dim testvar As String
sql = "INSERT INTO dbo_OrderHeader " _
& "(OrdCusID, OrdDate, OrdStatus, OrdValue, OrdNotes, OrdPostageID, OrdDelAddID,OrdBatchID,OrdPaymentMethod, OrdCourierID,ordAgentID, OrdOutstanding,OrdSource) " _
& " VALUES ('" & CustomerID & "' ,'" & OrderDate & "', '" & OrderStatus & "', '" & OrderValue & "', '" & OrderNotes & "', '" & OrderPostageID & "','" & OrderAddressID & "','" & OrderBatchID & "','" & OrderPayment & "','" & OrderCourierID & "','" & OrderAgentID & "','" & OrderOutstanding & "', 1)"
DoCmd.RunSQL (sql)
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
MsgBox ("Succes - OrderHeader" & " '" & IDT & "' ")
End Sub
I was expecting a result from this code:
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
But that gives me "0" as result.
Can you help please.
Thanks
You can try this :
Set db = CurrentDB
db.Execute(sql)
IDT = db.OpenRecordset("SELECT ##IDENTITY")(0)
Set db = Nothing
NOTE
Don't execute your insert query like DoCmd.RunSQL (sql) Instead follow the above approach.
sqlcon = New MySqlConnection
sqlcon.ConnectionString = "server=localhost;userid=root;password=soumya;database=bams;"
Dim da, da1 As MySqlDataAdapter
Dim ds, ds1 As New DataSet
Dim attendedclass, noofclass As Integer
Dim query, query1 As String
Dim yr, mon, day, yr1, mon1, day1 As Integer
yr = DateTimePicker1.Value.Year
yr1 = DateTimePicker2.Value.Year
day = DateTimePicker1.Value.Day
day1 = DateTimePicker2.Value.Day
mon = DateTimePicker1.Value.Month
mon1 = DateTimePicker2.Value.Month
sqlcon.Open()
query1 = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "' ) and ( SUBJECT='" & ComboBox1.SelectedItem.ToString() & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( CLASS ='" & ComboBox2.SelectedItem.ToString() & "' ) and ( DAY between " & day & " and " & day1 & ") and ( MONTH between " & mon & " and " & mon1 & " ) and (YEAR between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query1, sqlcon)
da1 = New MySqlDataAdapter(sqlcom)
da1.Fill(ds1)
noofclass = ds1.Tables(0).Rows.Count()
query = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "') and ( SUBJECT='" & ComboBox1.SelectedItem.text & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( ATTENDENCE='P' ) and ( CLASS ='" & ComboBox2.SelectedItem.ToString() & "' ) and ( DAY between " & day & " and " & day1 & ") and ( MONTH between " & mon & " and " & mon1 & " ) and (YEAR between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query, sqlcon)
da = New MySqlDataAdapter(sqlcom)
da.Fill(ds)
attendedclass = ds.Tables(0).Rows.Count()
DataGridView1.DataSource = ds
sqlcon.Close()
i cannot store date in mysql data base , cz i cld nt convert the format of datetimepicker n vb , . now i hve split the values of dtpicker and stored it as integer n data base ,.. need help to execute the query .. help plz .. ty
replace this query and check. In your query you used fields day,month and year are keywords, so add brackets with that table fields in the where clause and check
sqlcon = New MySqlConnection
sqlcon.ConnectionString = "server=localhost;userid=root;password=soumya;database=bams;"
Dim da, da1 As MySqlDataAdapter
Dim ds, ds1 As New DataSet
Dim attendedclass, noofclass As Integer
Dim query, query1 As String
Dim yr, mon, day, yr1, mon1, day1 As Integer
yr = DateTimePicker1.Value.Year
yr1 = DateTimePicker2.Value.Year
day = DateTimePicker1.Value.Day
day1 = DateTimePicker2.Value.Day
mon = DateTimePicker1.Value.Month
mon1 = DateTimePicker2.Value.Month
sqlcon.Open()
query1 = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "' ) and ( SUBJECT='" & ComboBox1.SelectedText.ToString() & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( CLASS ='" & ComboBox2.SelectedText.ToString() & "' ) and ( `DAY` between " & day & " and " & day1 & ") and ( `MONTH` between " & mon & " and " & mon1 & " ) and (`YEAR` between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query1, sqlcon)
da1 = New MySqlDataAdapter(sqlcom)
da1.Fill(ds1)
noofclass = ds1.Tables(0).Rows.Count()
query = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "') and ( SUBJECT='" & ComboBox1.SelectedText.text & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( ATTENDENCE='P' ) and ( CLASS ='" & ComboBox2.SelectedText.ToString() & "' ) and ( `DAY` between " & day & " and " & day1 & ") and ( `MONTH` between " & mon & " and " & mon1 & " ) and (`YEAR` between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query, sqlcon)
da = New MySqlDataAdapter(sqlcom)
da.Fill(ds)
attendedclass = ds.Tables(0).Rows.Count()
DataGridView1.DataSource = ds
sqlcon.Close()
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
This is my code for populating the datagridview:
Public Sub generate_list_ftMK(ByVal clbBranch As CheckedListBox, ByVal dtpSDate As DateTimePicker, ByVal dtpEDate As DateTimePicker, ByVal dvList As DataGridView)
Dim ds As DataSet = New DataSet()
Dim da As MySqlDataAdapter
Dim strQ As String = String.Empty
Dim strQ1 As String = String.Empty
Dim colItemCode As String = String.Empty
Dim colReg_Pri As String = String.Empty
Dim colXL_Pri As String = String.Empty
Dim colDel_Date As String = String.Empty
Dim colLabel As String = String.Empty
Dim colDays As String = String.Empty
Dim PCT As String = String.Empty
Try
If con.State = ConnectionState.Open Then con.Close()
con.Open()
'clear the dataset
ds.Tables.Clear()
'loop for all branches
For i = 0 To clbBranch.CheckedItems.Count - 1
Application.DoEvents()
'get the Branch Code
chkBranch = clbBranch.CheckedItems(i).ToString
'select item code and price where JO_TYPE is JO
strQ = "select " & _
"CONCAT(a.STYLE_CODE, '-', LPAD((a.JO_NO), 4, '0'), '-', d.LINE_NO) as Item_Code, " & _
"DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d') as DEL_DATE, " & _
"d.REG_PRI as Reg_Price, " & _
"d.XL_PRI as XL_Price, " & _
"a.LABEL_CODE, " & _
"a.STYLE_CODE, " & _
"LPAD((a.JO_NO), 4, '0')," & _
"d.LINE_NO, " & _
"DATEDIFF('" & Format(Date.Now, "yyyy-MM-dd") & "',DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d')) as Days " & _
"from " & _
"jo_hdr as a " & _
"inner join " & _
"branch as b ON a.BRNCH_CODE = b.BRNCH_CODE " & _
"inner join " & _
"dr_hdr as c ON c.TRAN_REF = a.TRAN_NO " & _
"inner join " & _
"dr_det as d ON d.DR_NO = c.DR_NO " & _
"where " & _
"c.DEL_DATE BETWEEN '" & dtpSDate.Text & "' AND '" & dtpEDate.Text & "' " & _
"and a.LABEL_CODE = '" & FtMK_Code & "' " & _
"and a.BRNCH_CODE = '" & chkBranch & "' " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.REG_PRI) - 1,2) = 75 " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.XL_PRI) - 1,2) = 75 "
cmd = New MySqlCommand(strQ, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "tblJO")
For r = 0 To ds.Tables("tblJO").Rows.Count - 1
Application.DoEvents()
colItemCode = ds.Tables("tblJO").Rows(r)(0).ToString
colDel_Date = ds.Tables("tblJO").Rows(r)(1).ToString
colReg_pri = ds.Tables("tblJO").Rows(r)(2).ToString
colXL_pri = ds.Tables("tblJO").Rows(r)(3).ToString
colLabel = ds.Tables("tblJO").Rows(r)(4).ToString
sumStyle = ds.Tables("tblJO").Rows(r)(5).ToString
sumJO = ds.Tables("tblJO").Rows(r)(6).ToString
sumNo = ds.Tables("tblJO").Rows(r)(7).ToString
colDays = ds.Tables("tblJO").Rows(r)(8).ToString
'for the number to decimal
colReg_pri = FormatNumber(colReg_pri, 2)
colXL_pri = FormatNumber(colXL_pri, 2)
'get the total quantity and the branch quantity
get_TotalQty_and_BranchQty()
'if the branch quantity is zero
If branchQty = 0 Then
PCT = "N\A"
Else
'compute the percent sold
PCT = totalQty
End If
dvList.Rows.Add(False, colItemCode, PCT, colDel_Date, Format(Date.Now, "yyyy-MM-dd"), colDays, _
colReg_Pri, colXL_Pri, colLabel, "JO", dtpSDate.Text, dtpEDate.Text, _
clbBranch.CheckedItems(i).ToString, mkType)
Next
Next
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
I have use indexes in my tables, and also add application.doevents. Is there anything I could do to make the populating in the datagridview faster with this code? I'm trying to search about making the datagridview doublebuffered because I read it online that I will make the datagridview faster but I have no idea how to use it.
Any help will be appreciated, Thank you.
Your issue is using
Application.DoEvents
I'm not going to get into the details of why this is bad practice, try using a Background Worker instead.