Retrieving data between two dates from Access database using VB.NET - 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)

Related

Error: No value given for one or more required parameters. What does this mean? How do I fix?

I'm creating a program in which users can see a table from an access database in a DataGridView.
However, when pressing "btnDisplay" the program crashes and highlights this line:
da.Fill(ds, "tblOrders")
The error reads: "No value given for one or more required parameters"
What does this mean and how do I fix it?
Here is the code:
Imports System.Data.OleDb
Public Class frmViewTables
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub btnDisplayDataGrid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDataGrid.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [tblOrders] where Username = #username", MyConn)
cm.Parameters.Add(New OleDbParameter("#username", OleDbType.VarChar, 255, frmLogin.SuccessfulLoginUsername))
cm.Parameters("#username").Value = frmLogin.SuccessfulLoginUsername
da.Fill(ds, "tblOrders")
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvDynamic.DataSource = view
End Sub
Things seem a little messed up. I am not sure about the rest of it but this should solve your parameter problem.
Dim source1 As New BindingSource
Dim ds = New DataSet
Dim tables = ds.Tables
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb")
Dim da As OleDbDataAdapter = New OleDbDataAdapter()
Dim cmd As New OleDbCommand("Select * from [tblOrders] where Username = #username", cn)
cmd.Parameters.Add("#username", OleDbType.VarChar, 255).Value = frmLogin.SuccessfulLoginUsername
da.SelectCommand = cmd
da.Fill(ds, "tblOrders")
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvDynamic.DataSource = view

how to add data in sql database with datagridview

heres my code in adding data to sql database
Dim ConStr As String = "Data Source=SYSTEMS-LAPTOP\DEVSQL;Initial Catalog=ContactDB;Persist Security Info=True;User ID=sa;Password=P#ssw0rd123"
Dim sql As String = "SELECT * FROM dataContactDB"
Dim sqlCon As New SqlConnection
Dim sqlCmd As New SqlCommand
Dim sqlAdapter As SqlDataAdapter
Dim sqlBuilder As SqlCommandBuilder
Dim sqlDataset As DataSet
Dim sqlTable As DataTable
this code loads my data in datagridview from sqldatabase
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sqlCon = New SqlConnection(ConStr)
sqlCon.Open()
sqlCmd = New SqlCommand(sql, sqlCon)
sqlAdapter = New SqlDataAdapter(sqlCmd)
sqlBuilder = New SqlCommandBuilder(sqlAdapter)
sqlDataset = New DataSet
sqlAdapter.Fill(sqlDataset, "dataContactDB")
sqlTable = sqlDataset.Tables("dataContactDB")
sqlCon.Close()
dgData.DataSource = sqlDataset.Tables("dataContactDB")
dgData.ReadOnly = True
dgData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
my codes in adding data to sqldatabase
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
sqlCon.Open()
sqlCmd.CommandText = "insert into dataContactDB(con_Name,con_Phone,Address,Company,Gender) values('" & txtName.Text & "','" & txtPhone.Text & "','" & txtAddress.Text & "','" & txtCompany.Text & "','" & txtGender.Text & "')"
sqlCmd.ExecuteNonQuery()
sqlCon.Close()
End Sub
all i want to do is when you add data in sqldatabase. datagridview will retrieve the new added data and add it on its list. every time i add data . datagridview didnt show my recent added data, how do i do that?
You simply have to reload the data in grid. Put all code the in a function named LoadMyGrid, that you have written in frm_load. Now call this method from frm_load. Also call same method in your button click event in the last line.

check values of column in sql

I am trying to collect values from a database, and if they are X value sett he background colour to green.
Basically, I have a Rota system, and if the user is working, then change the background colour. The select * will only bring back 1 row ever.
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class Form4
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form4_Load(sender As Object, e As EventArgs)
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
Dim strSQL As String = "SELECT * from Users"
Dim da As New SqlDataAdapter(strSQL, Con)
Dim ds As New DataSet
da.Fill(ds, "Users")
With cboname
.DataSource = ds.Tables("Users")
.DisplayMember = "Name"
.ValueMember = "Id"
.SelectedIndex = 0
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
sqlstring = ("SELECT * FROM Rota WHERE UserId ='" & cboname.SelectedIndex & "' and ID ='" & dtp1.Value & "'")
da = New SqlDataAdapter(sqlstring, Con)
ds = New DataSet
da.Fill(ds, "Rota")
End Sub
End Class
After this, I understand I need to get a few IF statements, but I am unsure on how to construct them.
To check a value in a DataSet use first get a DataTable inside of it, then a DataRow, then check one of the field values:
ds.Tables(0).Rows(0)("{field name}");
So to change the color based on some value:
If ds.Tables(0).Rows(0)("{field name}") = "Red" Then
textbox1.BackColor = Color.Red
End If
Some other comments:
A DataSet may be a bit heavy for getting one value (unless you're binding to a control). You can just use ADO.NET objects and use ExecuteScalar)
It's safer to use parameters instead of concatenating SQL statements (prevents SQL Injection and errors from special characters)
You can refactor your code to put the connection string in a single location rather than duplicating it across methods.

getting variables into sql string from list box

I am having a problem trying to get the contents of a list box into and SQL string via a variable(moon)
Here are 3 SELECT strings from the main body of code below.The last two strings work fine
but the first one doesn't.That's the one where I try and place the variable into the code
I have tried a few variations on the code but nothing seems to work.Does anybody have any suggestions.
THE SQL STRINGS:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon "' ", myConnection) 'fails
da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works{
MAIN CODE BODY
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As DataSet = New DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim moon As String
moon = ListBox1.Text
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
connString = provider & dataFile
myConnection.ConnectionString = connString
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection) 'fails
'da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
'da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works
da.Fill(ds, "books")
' replace "items" with the name of the table
' replace [Item Code], [Description], [Price] with the columns headers
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub
End Class
Best practice is to use a new connection object for each call to the database, define objects with the smallest scope possible, and to use parameterized queries instead of substituting the value into your sql string.
Under no circumstances should you ever use string manipulation to put a user-selected value into your sql statement! Code like this is very bad:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection)
Imagine what would happen in this example if you have an author like "Patrick O'Neil". There are many ways this problem can be further abused to cause real damage to your database, application, and users. Just don't use string concatenation for this.
Do it like this instead:
Public Class Form1
Private Const provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Private Const dataFile As String = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
Private connString As String = provider & dataFile
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ds As New DataSet()
'Set a special placeholder for your value as part of a *constant* sql statement
Dim sql As String = "SELECT * FROM books WHERE [author] = ? "
Using cn As New OleDbConnection(connString), _
cmd As New OleDbCommand(sql, cn), _
da As New OleDbDataAdapter(cmd)
'Set the value for that placeholder via a query parameter
'Parameters work best when you set the actual type and length
' to match your database. I had to guess at the length here.
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = Listbox1.Text
da.Fill(ds, "books")
End Using
DataGridView1.DataSource = ds.Tables("books")
DataGridView1.Refresh()
End Sub
End Class

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