Trouble converting a date to a string and passing to SQL - vb.net

I'm getting the following error message:
System.InvalidCastException: Conversion from string "select * from [tbl_FBNK_Limit_Hi" to type 'Integer' is not valid.
My setup is really pretty simple. Here is all the code:
Imports System.Data.OleDb
Public Class Form1
'Change Path Here:
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=path_here.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim SqlStr As String
Dim startDate As String
Dim endDate As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
Dim startDate As DateTime = DateTimePicker1.Value.ToString("MM/dd/yyyy")
Dim endDate As DateTime = DateTimePicker2.Value.ToString("MM/dd/yyyy")
SqlStr = "select * from [tbl_Hist_Current] where AsOfDate >= #" & startDate & "# and AsOfDate <=#" & endDate & "#"
da = New OleDbDataAdapter(SqlStr, MyConn)
da.Fill(SqlStr, "tbl_Limit_Hist_Current")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
End Class
When I copy/paste the SqlStr into Access it works fine, so it's gotta be something with the way the dates are being handled, or not handled. Can someone here give me a nudge in the right direction?
Private Sub LoadData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=server_name;Initial Catalog=database_name;Integrated Security=True"
Dim SqlStr As String
Dim startDate As DateTime = DateTimePicker1.Value.ToString("MM/dd/yyyy")
Dim endDate As DateTime = DateTimePicker2.Value.ToString("MM/dd/yyyy")
SqlStr = "Select Field1, Field2, Field3, AsOfDate FROM [TBL_DATA_HIST] where AsOfDate >= '" & startDate & "' and AsOfDate <='" & endDate & "'"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(SqlStr, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "TBL_DATA_HIST")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "TBL_DATA_HIST"
' Count rows in DG
Dim int As Integer
int = DataGridView1.Rows.Count()
TextBox1.Text = int
End Sub

You can use the following solution, using parameter placeholders:
'Change Path Here:
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=path_here.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim SqlStr As String
Dim startDate As String
Dim endDate As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
Dim startDate As DateTime = DateTimePicker1.Value
Dim endDate As DateTime = DateTimePicker2.Value
SqlStr = "select * from [tbl_Limit_Hist_Current] where AsOfDate >= ? and AsOfDate <= ?"
da = New OleDbDataAdapter(SqlStr, MyConn)
Dim selectCMD As New OleDbCommand(SqlStr, MyConn)
da.SelectCommand = selectCMD
selectCMD.Parameters.Add("#AsOfDate1", OleDbType.Date).Value = startDate
selectCMD.Parameters.Add("#AsOfDate2", OleDbType.Date).Value = endDate
ds = New DataSet
da.Fill(ds, "tbl_Limit_Hist_Current")
tables = ds.Tables
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
You should also remove the ToString("MM/dd/yyyy") on the DateTimePicker values. On my system (german setup - dd.mm.yyyy date format by default) I got an error message like the following:
Invalid conversion of the string 11.13.2017 to type Date - translated from german
As Joel Coehoorn also mentioned in the comments, is it a performance waste and in some situations a security issue.

Related

It gives value in textbox but only after finishing it . how to display data while running timer?

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Me.TextBox1.Text = "hello"
Dim connectionString As String = "Data Source=192.168.0.199;Initial Catalog=NEWDATABASE;Persist Security Info=True;User ID=admin;Password=123456"
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "SELECT TOP (" & topvalue & ") * FROM [NEWDATABASE].[dbo].[MachineParameter] WHERE status = '0' ORDER BY Id ASC"
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
dataadapter.Fill(ds, "table")
DataGridViewtx.DataSource = ds
DataGridViewtx.DataMember = "table"
connection.close()
end sub

Binding a Data Set/Table to a DataGridView

I am currently writing a simple stock control Visual Basic program linked to a database.
Here's what it looks like so far.
The form displays the data in a DataGrid View and I am trying to refresh my DataGridView automatically when data is changed (using SQL) in the database I am using.
After doing some research I have found that the best way to do this is by binding the data table (using BindingSource) to the DataGridView
However I am struggling to implement this, as every implementation I have tried results in a blank DataGridView and would thoroughly appreciate it if someone could assist me.
Here's the code:
Imports System.Data.OleDb
Public Class Form1
Public connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbStock.accdb"
Public conn As New OleDb.OleDbConnection(connectionString)
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TblStockControlTableAdapter.Fill(Me.DbStockDataSet.tblStockControl)
For i As Integer = 1 To 5
ComboBoxQty1.Items.Add(i)
ComboBoxQty2.Items.Add(i)
Next
Dim SqlQuery As String = "Select tblStockControl.[EggType] FROM tblStockControl"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
'DataGridView1.DataSource = dt
For Each row As DataRow In dt.Rows
ComboBoxAdd.Items.Add(row.Item(0))
Next
For Each row As DataRow In dt.Rows
ComboBoxTake.Items.Add(row.Item(0))
Next
End Sub
Private Sub btnAddEgg_Click(sender As Object, e As EventArgs) Handles btnAddEgg.Click
conn.Open()
Dim SqlQuery As String = "Select tblStockControl.[Quantity] FROM tblStockControl WHERE EggType = '" & ComboBoxAdd.Text & "'"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Dim qty As Integer = 0
For Each row As DataRow In dt.Rows
For Each column As DataColumn In dt.Columns
qty = row(column)
Next
Next
Dim NewQty As Integer = qty + CInt(ComboBoxQty2.Text)
UpdateAddQty(NewQty)
conn.Close()
End Sub
Function UpdateAddQty(ByRef NewQty As Integer) As Integer
Dim SqlUpdate As String = "UPDATE tblStockControl SET Quantity = '" & NewQty & "' WHERE EggType = '" & ComboBoxAdd.Text & "'"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Connection = conn
.ExecuteNonQuery()
End With
Return (Nothing)
End Function
Private Sub btnViewStock_Click(sender As Object, e As EventArgs) Handles btnViewStock.Click
'Add code to open Access file.
End Sub
Private Sub btnTakeEgg_Click(sender As Object, e As EventArgs) Handles btnTakeEgg.Click
conn.Open()
Dim SqlQuery As String = "Select tblStockControl.[Quantity] FROM tblStockControl WHERE EggType = '" & ComboBoxTake.Text & "'"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Dim qty As Integer = 0
For Each row As DataRow In dt.Rows
For Each column As DataColumn In dt.Columns
qty = row(column)
Next
Next
Dim NewQty As Integer = CInt(ComboBoxQty1.Text) - qty
UpdateTakeQty(NewQty)
conn.Close()
End Sub
Function UpdateTakeQty(ByRef NewQty As Integer) As Integer
Dim SqlUpdate As String = "UPDATE tblStockControl SET Quantity = '" & NewQty & "' WHERE EggType = '" & ComboBoxTake.Text & "'"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Connection = conn
.ExecuteNonQuery()
End With
Return (Nothing)
End Function
End Class
If you are using a DataTable , then reset the dataasource of the DataGridView.I mean you need to read data from the database again. :
'Do this every time you add/Update a data
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Or you can just create a row for every data you add to your database :
'Do this every time you add a data
DataGridViewRow row = (DataGridViewRow)DataGridView1.Rows[0].Clone()
row.Cells[0].Value = "Alex"
row.Cells[1].Value = "Jordan"
DataGridView1.Rows.Add(row)

an error when choosing between two specific date in datagridview in VISUAL BASIC

i wrote a code for searching between two specific date in Visual Basic and it was run correctly.
but now there's a problem.
- when i chose between two date in DECEMBER that i inserted a data in, it show correctly.
-- but when i chose two date in month before that doesn't have any data it show the DECEMBER data.
-- also when i chose a date in DECEMBER and the another in JANUARY there's no data!
i use MS Access for my data base -
here is my code...
Imports System.Data.OleDb
Imports System.Data.DataTable
Public Class p2
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sh\Desktop\FP\Fproject.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim Str As String
Public dr As OleDbDataReader
Private Sub p2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Str = "SELECT * FROM att WHERE (date1 between '" & Me.DateTimePicker1.Value.ToShortDateString & "' and '" & Me.DateTimePicker2.Value.ToShortDateString & "')"
Dim cmd As OleDbCommand = New OleDbCommand(Str, MyConn)
dr = cmd.ExecuteReader
While dr.Read()
If dr.HasRows Then
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select id1 from [att] where (date1 >= '" & Me.DateTimePicker1.Value.ToShortDateString & "' and date1 <= '" & Me.DateTimePicker2.Value.ToShortDateString & "')", MyConn)
da.Fill(ds, "att")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
Return
End If
End While
MsgBox("no data for this chosen date", MsgBoxStyle.Exclamation, "Warning")
DateTimePicker1.Value = Now
Return
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
FirstForm.Show()
Me.Hide()
End Sub
End Class

vb.net Listboxes and sql

I have 4 List boxes that I check,the contents of which go to make up the variables that get placed into the sql statement.This works fine.The problem is I have to check ALL of the boxes.If I leave any of the boxes out the sql statement doesn't work. I Did try adding "" to the listbox but this didn't work and it looked messy.Is there a way around this.Many Thank Jim
HERE IS MY CODE:
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Dim aa As String = authorList.Text
Dim bb As String = publisherList.Text
Dim cc As String = yearpublishedList.Text
Dim dd As String = genreList.Text
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source =C:\Documents and Settings\james\Desktop\Authors.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM books WHERE author = '" & aa & "' AND publisher = '" & bb & "' AND yearpublished = '" & cc & "' AND genre = '" & dd & "' "
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Authors")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
'MsgBox("OPEN FOR LUNCH")
'MsgBox("CLOSED FOR THE DAY")
con.Close()
End Sub
End Class
You are parsing the checkboxes into a string, so when you do that, you get:
1,2,3,4,5,6,7
If you do not select one checkbox, it will look like this:
1,2,3,,5,6,7
So SQL will break
Several ways you can approach this to solve the issue, so I'm not going to attempt one. But this should hopefully explain to you what happens and why it happens so you can go ahead and fix

How to view data between two dates in vb.net using the datetimepicker

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim ds As New DataSet
Dim dt As New DataTable
Dim dfrom As DateTime
Dim dto As DateTime
Dim da As New SqlDataAdapter
dfrom = dtpicker1.Text
dto = dtpicker2.Text
cn.ConnectionString = "Data Source=JMI-PC\SQLEXPRESS;Initial Catalog=student_system;User Id=ian;Password=rockstar"
cn.Open()
Dim str As String
Format(dtpicker1.Text, "yyyy-MM-dd")
Format(dtpicker2.Text, "yyyy-MM-dd")
str = "select Exam_Date from class1 where Exam_Date= '" & dtpicker1.Text & "' and Exam_Date='" & dtpicker2.Text & "'"
da = New SqlDataAdapter(str, cn)
da.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.DataSource = dt
End Sub
i am trying to view data between two dates using the datetimepicker and when i try to run this code i get an error aying " Conversion failed when converting date and/or time from character string." if anyone can show me how its done, i would really appreciate it
You need to check your date range in your SQL statment
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim ds As New DataSet
Dim dt As New DataTable
Dim dfrom As DateTime = dtpicker1.Value
Dim dto As DateTime = dtpicker2.Value
cn.ConnectionString = "Data Source=JMI-PC\SQLEXPRESS;Initial Catalog=student_system;User Id=ian;Password=rockstar"
cn.Open()
Dim str As String = "select Exam_Date from class1 where Exam_Date >= '" & Format(dFrom, "MM-dd-yyyy") & "' and Exam_Date <='" & Format(dto, "MM-dd-yyyy") & "'"
Dim da As SqlDataAdapter = New SqlDataAdapter(str, cn)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub