vb.net Listboxes and sql - 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

Related

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

Why is my database not updating?

My problem is that when I am editing cells in the datagrid the database is not updating.
The code I used is below.
Public Class Form9
Inherits System.Windows.Forms.Form
Dim sql As String = "SELECT * FROM User_Account WHERE IsAdmin=False"
Dim conn As New OleDb.OleDbConnection
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
Dim da As New OleDb.OleDbDataAdapter(sqlCom)
Dim dt As New DataTable
Private Sub Form9_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Load
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & _
folderpath & "\TKIC\TKIC_Data_Storage.accdb'" & _
";Persist Security Info=True"
conn.Open()
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
DataGridView1.Update()
dt.AcceptChanges()
End Sub
End Class
You have to update the underlying DataTable. The DataGridView.Update causes the control to redraw the invalidated regions within its client area (basically repaints). The dt.AcceptChanges() only commits the changes in the DataTable not the database. The database has to be updated explicitly using the adapter and appropriate command texts. The OleDbCommandBuilder helps in forming the appropriate command texts.
Use the OleDbDataAdapter to update the database.
OleDbCommandBuilder cb = new OleDbCommandBuilder(adapter);
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
adapter.Update(datatable);

Syntax error in INSERT INTO statement generated by OleDbCommandBuilder

Why does this keep telling me
Syntax error in INSERT INTO statement
I searched for more details but it keeps telling me this.
This is the code :
Imports System.Data
Imports System.Data.OleDb
Public Class f9
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim sql As String
Private Sub f9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = "Provider=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = E:\21.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM snack"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "snack")
da = New OleDb.OleDbDataAdapter(sql, con)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles b1.Click
Me.Close()
x = x + (5 * 1)
If d.tc.Text = f7.b1.Text Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("snack").NewRow()
dsNewRow.Item("Date") = f1.d1.Text
dsNewRow.Item("Order") = d.tc.Text
dsNewRow.Item("Number Of Items") = b1.Text
dsNewRow.Item("Price") = " 5 "
dsNewRow.Item("Total") = x
ds.Tables("snack").Rows.Add(dsNewRow)
da.Update(ds, "snack")
con.Close()
End If
End Sub
End Class
Some of your field names are reserved words in Access SQL (Date, Order) and you also have a field name with spaces in it. The default configuration of the CommandBuilder will not produce valid SQL statements in cases like this.
To fix this issue, immediately after the line...
Dim cb As New OleDb.OleDbCommandBuilder(da)
...add the following two lines:
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will tell the command builder to enclose table and field names in square brackets ([]) so instead of generating a statement like
INSERT INTO snack (Date, Order, Number Of Items) VALUES ...
it will generate a statement like
INSERT INTO [snack] ([Date], [Order], [Number Of Items]) VALUES ...
Those square brackets are required for the SQL statement to be syntactically correct.

Syntax error (missing operator) in query expression 'Prod_Num ='

This Syntax error (missing operator) in query expression 'Prod_Num ='. always shows up when I'm trying to search an item in the database. Please help me.
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim sql As String
Dim dbp As String
Dim dbs As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbp = "Provider = Microsoft.ACE.OLEDB.12.0;"
dbs = "Data Source=" & Application.StartupPath & "/POS.accdb"
con.ConnectionString = dbp & dbs
con.ConnectionString = dbp & dbs
con.Open()
sql = "SELECT * FROM tblInventory"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPNum.Focus()
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
txtPNum.Text = ""
sql = "SELECT * FROM tblInventory WHERE Prod_Num =" & txtPNum.Text
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
My guess is that you have problem here:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
txtPNum.Text = "" ' <-----------------
sql = "SELECT * FROM tblInventory WHERE Prod_Num =" & txtPNum.Text
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
Remove this line:
txtPNum.Text = ""
Since you always clears the txtPNum textbox's text before passing it to the query.
NOTE:
Don't forget to implement it via parameterized query. This is not a good approach.
See parameterized query examples:
Example 1
Example 2
Hope it helps!
does txtPNum.Text contain any data?
Why don't you try checking that, because if it is empty your running SQL statement is "SELECT * FROM tblInventory WHERE Prod_Num =" which would raise that error.
Also if the Prod_Num column is integer, perhaps you should use int(txtPNum.Text) if that value is a string, this would also prevent SQL Injection.
In addition to the problem with txtPNum.Text that others have pointed out, I would recommend a couple of other things:
Use parameterized queries to avoid SQL Injection.
Use Using blocks with your connection, and close the connection as soon as you are done. In your Form_Load, for example, you open the connection and leave it open. That is not good practice.
Example:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim dbp As String
Dim dbs As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbp = "Provider = Microsoft.ACE.OLEDB.12.0;"
dbs = "Data Source=" & Application.StartupPath & "/POS.accdb"
Using con As OleDbConnection = New OleDbConnection(dbp & dbs)
con.Open()
da = New OleDbDataAdapter("SELECT * FROM tblInventory", con)
da.Fill(dt)
dgList.DataSource = dt
End Using
txtPNum.Focus()
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
Using con As OleDbConnection = New OleDbConnection(dbp & dbs)
con.Open()
da = New OleDbDataAdapter("SELECT * FROM tblInventory WHERE Prod_Num = #ProdNum", con)
da.SelectCommand.Parameters.AddWithValue("#ProdNum", txtPNum.Text)
da.Fill(dt)
dgList.DataSource = dt
End Using
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
I would also recommend adding some Try Catch blocks to handle errors, and you may need to convert the values you're assigning to text boxes if they're something other than String.

Visual Basic 2008 New Search Query

I'm trying to do a search through an access database I added to a project but I get this error: An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll"
Additional information: No value given for one or more required parameters.
The idea was to search the database for text entered into a textbox, then display the information on that row within more text boxes.
The code dr = cmd.ExecuteReader is also highlighted as an issue when debugging. I'm using visual basic 2008, and quite new to the whole coding scene so explanations as to why the issue has occurred would be appreciated!
Imports System.Windows.Forms
Imports System.Data.OleDb
Public Class frmSearch
Public con As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim dbProvider As String
Dim dbSource As String
Dim BillingSystemFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Private Sub frmSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'BillingdatabaseDataSet.BillingInfo' table. You can move, or remove it, as needed.
Me.BillingInfoTableAdapter.Fill(Me.BillingdatabaseDataSet.BillingInfo)
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
'Setup the provider
TheDatabase = "/billingdatabase.accdb"
BillingSystemFolder = Application.StartupPath
FullDatabasePath = BillingSystemFolder & TheDatabase
'Set the database and the location of it
dbSource = "Data Source = " & FullDatabasePath
'Set the data source
con.ConnectionString = dbProvider & dbSource
'Set the connection string
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
txtJobNum.Clear()
txtName.Clear()
txtSurname.Clear()
Dim str As String
str = "SELECT * FROM BillingInfo WHERE (Code = " & CodeText.Text & ")"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
dr = cmd.ExecuteReader
While dr.Read()
txtSurname.Text = dr("Surname").ToString
txtName.Text = dr("First Name").ToString
txtJobID.Text = dr("Customer ID").ToString
End While
con.Close()
End Sub
End Class
Probably the field Code is a text field. In this case when you want to search using a particular value for that field you should enclose the value between single quotes.
Something like this
str = "SELECT * FROM BillingInfo WHERE (Code = '" & CodeText.Text & "')"
However this is really a bad practice because this allows to create an Sql Injection attack or it will simply fail because your value contains a single quote.
The correct method is using a parameterized query like this
str = "SELECT * FROM BillingInfo WHERE (Code = #p1)"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = CodeText.Text
dr = cmd.ExecuteReader