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

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

Related

Index out of range exception cannot find column

Hello I have this problem in came upon when trying to do simple manual search in vb.net. It says System.IndexOutOfRangeException: 'Cannot find column 4.'
could anyone explain what this means i am quite new to coding and dont quite get what i could to do fix this. In the attached database i have only one table called customer with 4 columns custid, custfname, custlname and dob.
This is the code and the error occurs in the btnNext and Navigaterecords. The database was made in sqlite
Imports System.Data.SQLite
Public Class Form1
Dim inc As Integer
Dim MaxRows As Integer
Dim ConnectionString As String = "Data Source=dbRoomBookings.db"
Dim ds As New DataSet
Dim dt As New DataTable
Dim mSQL As String = "SELECT * FROM Customer"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customer")
dt = ds.Tables(0)
MaxRows = ds.Tables("customer").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customer;"
dgvSearchResults.DataSource = display(msSQL, "customer")
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(4)
cboYear.Text = ds.Tables("Customer").Rows(inc).Item(5)
Else
MsgBox("no more rows")
End If
End Sub
Sub navigaterecords()
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(4)
cboYear.Text = ds.Tables("customer").Rows(inc).Item(5)
txtDbo.Text = ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(4) & "/" & ds.Tables("customer").Rows(inc).Item(5)
End Sub
Private Sub BtnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Private Sub BtnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
navigaterecords()
End If
End Sub
Private Sub BtnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
navigaterecords()
Else
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
If txtSearchFname.Text <> "" Then
sSQL = "SELECT * FROM customer WHERE custfname LIKE'" & txtSearchFname.Text & "%'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customer")
newdt = newds.Tables(0)
dgvSearchResults.DataSource = newdt
con.Close()
ElseIf txtSearchId.Text <> "" Then
sSQL = "SELECT * FROM customer WHERE custid ='" & txtSearchId.Text & "'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customer")
newdt = newds.Tables(0)
dgvSearchResults.DataSource = newdt
con.Close()
End If
End Sub
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim con2 As New SQLiteConnection
Dim da2 As New SQLiteDataAdapter
Dim dsql, qsql As String
Dim ds2 As New DataSet
Dim dt2 As DataTable
con2 = New SQLiteConnection(ConnectionString)
dsql = "DELETE FROM customer WHERE custid = " & txtSearchId.Text & ""
qsql = "SELECT * FROM customer"
Dim cmd As New SQLiteCommand(qsql, con2)
con2.Open()
da2.DeleteCommand = con2.CreateCommand
da2.DeleteCommand.CommandText = dsql
da2.DeleteCommand.ExecuteNonQuery()
MsgBox("Row(s) Deleted !! ")
Dim da3 As New SQLiteDataAdapter(cmd)
da3.Fill(ds2, "customer")
dt2 = ds2.Tables(0)
dgvSearchResults.DataSource = dt2
con2.Close()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim con3 As New SQLiteConnection
Dim da3 As New SQLiteDataAdapter
con3 = New SQLiteConnection(ConnectionString)
Dim usql As String = "UPDATE Customer SET custfname = '" & txtFname.Text & "'" & "WHERE custid =" & CInt(txtCusId.Text) & ""
con3.Open()
da3.UpdateCommand = con3.CreateCommand
da3.UpdateCommand.CommandText = usql
da3.UpdateCommand.ExecuteNonQuery()
MsgBox("Row Updated")
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim isql As String = "INSERT INTO customer(custfname, custlname, dob) VALUES('" _
& txtFname.Text & "','" & txtLname.Text & "','" & cboYear.Text _
& "-" & cboMonth.Text & "-" & cboDay.Text & "');"
Dim msql As String = "SELECT * FROM customer"
add(isql)
'refresh the Data Grid
dgvSearchResults.DataSource = display(msql, "customer")
End Sub
End Class
Here is the specific documentation on IndexOutOfRangeException: https://learn.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception
For visibility, the definition is:
The exception that is thrown when an attempt is made to access an
element of an array or collection with an index that is outside its
bounds.
In your case, you are trying to get a value by passing the index of a column but the index you're passing is greater than the total number of columns.
Assuming that your table definition has the following columns: custfname, custlname, and dob, the following represents when the Exception would occur:
Get column 0, returns the value of custfname
Get column 1, returns the value of custlname
Get column 2, returns the value of dob
Get column 3, throws an IndexOutOfRangeException
The same thing would also happen if you tried to get a value at a negative index too.
You have a 4-column table which will have indexes from 0 to 3 only:
custid is column 0, custfname is column 1, custfname is column 2, and dob is column 3.
So any attempt to access ds.Tables("customer").Rows(inc).Item(4) (and (5), etc) will yield an Index out of range exception.
But you seem to know that the table only has 4 columns; why are you then attempting to access columns that you know don't exist? I'm a bit confused by that. If you're trying to split DOB into day/month/year, you'll have to manipulate the dob value from the DOB composite column, Item(3).

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)

Trouble converting a date to a string and passing to SQL

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.

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

Retrieving data between two dates from Access database using VB.NET

I want to display data from a database in a datagridview. I am getting error on da.Fill(ds, "SAMPLE") with "data type mismatch error". Please see screenshot.
My date formats are 'short date' both datetimepicker and database values.
Imports System.Data.OleDb
Public Class Form1
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Recto D Sanchez Jr\Documents\sample.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
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
da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between '" & DateTimePicker1.Text & "' And '" & DateTimePicker2.Text & "'", MyConn)
da.Fill(ds, "SAMPLE")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
End Class
error screenshot
Since your DateTimePicker controls already deal with proper DateTime values you might have better luck using a parameterized query like this:
MyConn = New OleDbConnection(connString)
Dim cmd As New OleDbCommand("SELECT * FROM [SAMPLE] WHERE [LOGDATE] Between ? And ?", MyConn)
cmd.Parameters.AddWithValue("?", DateTimePicker1.Value.Date)
cmd.Parameters.AddWithValue("?", DateTimePicker2.Value.Date)
da = New OleDbDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "SAMPLE")
It would save you the trouble of dealing with different date formats, delimiting date literals, and other potential pitfalls.
Try
da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between #" & DateTimePicker1.Value.ToString("MM/dd/yyyy HH:mm:ss") & "# And #" & DateTimePicker2.Value.ToString("MM/dd/yyyy HH:mm:ss") & "#", MyConn)