Searching a database with a ComboBox - sql

for my college project I am designing a program that can read a Microsoft Access database about animals and display the data. I have managed to program it so that I can search by the animals name and it will display the records in a another form, but I need to be able to search other fields such as LatinName or AverageWeight and then display any results that have a match into a combo box which the user can then select and the program would display the code e.g. if I were to type in 50kg and there are two records with 50kg, it would display them both and then allow me to select which one I wanted.
Any help or advice would be much appreciated, fell free to ask if you need more information.
Public Class Form1
Private Sub btnsear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsear.Click
If (txtname.Text = "") Then
MsgBox("Invalid Search")
Else
Try
Dim newsql As String
newsql = "select * from Animals where AnimalName like " & "'%" & txtname.Text & "%'"
'MsgBox("select * from Animals where AnimalName like " & "'" & txtname.Text & "'")
'msgbox(newsql)
Dim con As New OleDb.OleDbConnection
Dim da As New OleDb.OleDbDataAdapter
' dim ds as NewDataTable
Dim dt As New DataTable("Animals")
' uses the 2010 compatible connection string
con.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Animals.accdb"
con.Open()
da = New OleDb.OleDbDataAdapter(newsql, con)
da.Fill(dt)
Form2.Show()
'show name in unbound text box
Form2.nametxt.Text = dt.Rows(0).Item(1)
Form2.latintxt.Text = dt.Rows(0).Item(2)
Form2.locationtxt.Text = dt.Rows(0).Item(3)
Form2.heighttxt.Text = dt.Rows(0).Item(4)
Form2.weighttxt.Text = dt.Rows(0).Item(5)
Form2.diettxt.Text = dt.Rows(0).Item(6)
Form2.statustxt.Text = dt.Rows(0).Item(7)
Form2.lifetxt.Text = dt.Rows(0).Item(9)
Form2.breedtxt.Text = dt.Rows(0).Item(10)
Form2.lengthtxt.Text = dt.Rows(0).Item(11)
Form2.txtimage.Text = dt.Rows(0).Item(12)
Form2.socialchk.Checked = dt.Rows(0).Item(8)
If dt.Rows(0).Item(8) = True Then
Form2.socialchk.Checked = True
Else
Form2.socialchk.Checked = False
End If
Catch
MsgBox("Item Not Found")
'con.close()
End Try
End If
If (txtopt.Text = "'") Then
Try
Dim newsql As String
newsql = "select * from Animals where AnimalName like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where LatinName like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where Location like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where AverageHeight like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where AverageWeight like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where DietaryNeeds like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where ConservationStatus like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where AverageLifeSpan like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where BreedingSeason like " & "'%" & txtopt.Text & "%'"
newsql = "select * from Animals where AverageLength like " & "'%" & txtopt.Text & "%'"
Catch
End Try
End If
End Sub

So you start the form with blank textboxes. You want to be able to search any of the textboxes by typing something in them. You should use multiple handles to get input from the textboxes, something like:
Private Sub searchByKeydown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles nameTxt.KeyDown, latintxt.KeyDown, locationtxt.KeyDown, heighttxt.KeyDown ' and all the rest of your textbox names
If e.KeyCode = Keys.Return Then ' This checks if the return key was pressed and will start the search
Dim tmpText As TextBox = DirectCast(sender, TextBox) ' grab the textbox that triggered the event
If tmpText.text = String.Empty Then ' enter was pressed without a search term
MsgBox("Please enter a search term")
Exit Sub
End If
Dim strSearchQuery As String = tmpText.text ' This is what the user wants to search
Select Case tmpText.name
Case "nameTxt"
' put in your search routine here for this textbox
Case "latintxt"
' put in your search routine here for this textbox
Case "locationtxt"
' put in your search routine here for this textbox
Case "heighttxt"
' put in your search routine here for this textbox
End Select
End If
End Sub
You will have more case statements, but this should get you going. Since you can already search by name, it's just a matter of changing the SQL statement for the other searches.

Per NiteTrip's answer, I believe you would also need to set the KeyPreview property of the form to TRUE so that it will pick up the keypress.

Related

filtering datagridview data using "NOT LIKE" condition is unsuccessful.how to modify the code?

I am developing a simple library management system. i try to filter data with "NOT LIKE" condition. the following code which i use is working, no errors.But gives mixed results.when i filter only "Gunasena" in publisher data rows with Added_Date.but this gives Gnasena+godage datas.Added_Date filter is totally correct.Help me to solve this problem,Thanks. this code works 100% correct in "LIKE" condition.
Private Sub combobox4_TextChange(sender As Object, e As EventArgs) Handles combobox4.TextChange
Dim filters As New List(Of String)
If combobox1.Text = "Added Date" And withoutButton.Checked Then
filters.Add("[Added_Date] LIKE '" & combobox2.Text & "%' And [Author] NOT LIKE '" &
combobox4.Text & "%'")
End If
If combobox1.Text = "Added Date" And withoutButton.Checked Then
filters.Add("[Added_Date] LIKE '" &
combobox2.Text & "%' And [Publisher] not LIKE '" & combobox4.Text & "%'")
End If
BooksBindingSource.Filter = String.Join(" Or ", filters)
End Sub

Syntax error: Missing operand after 'ID' operator

i know theres loads of posts with this problem, but i cant seem to find the error in my code, any ideas?
heres my code:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
On Error GoTo SearchErr
If txtSearch.Text = "" Then
Exit Sub
Else
Dim cantFind As String = txtSearch.Text
MainBindingSource.Filter = "(Convert(ID, 'System.String') LIKE '" & txtSearch.Text & "')" & _
"OR (Student ID LIKE '" & txtSearch.Text & "') OR (First Name LIKE '" & txtSearch.Text & "')" & _
"OR (Last Name LIKE '" & txtSearch.Text & "')"
If MainBindingSource.Count <> 0 Then
With dgvStudentInfo
.DataSource = MainBindingSource
End With
Im trying to search an Access DB in Vb.net
I think SQL is seeing "Student ID" as two words. If your table fields really have spaces in them you need to add brackets, "[Student ID]". (You may need single or double quote identifiers instead of brackets. Not sure.)

search using multiple criteria vb.net

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn.Open()
Dim sql = "SELECT * FROM [maint]"
dt.Clear()
If R1.Checked Then sql = sql & " where datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " [centr] ='" & Me.centra.Text & "'"
If R3.Checked Then sql = sql & "and [Priorité] ='" & Me.Priorite.Text & "'"
If R4.Checked Then sql = sql & "and [Etat_intervention] ='" & Me.etat.Text & "'"
Dim adapter As New OleDbDataAdapter(sql, MyConn)
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
MyConn.Close()
End Sub
problem =Syntax error in FROM clause. I want to search using multiple critera using checkbox R1 R2 R3 R4 and the resultat in my datagridview
You need to add a space between your search statements:
If R1.Checked Then sql = sql & " where datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " [centr] ='" & Me.centra.Text & "' "
If R3.Checked Then sql = sql & " and [Priorité] ='" & Me.Priorite.Text & "' "
If R4.Checked Then sql = sql & " and [Etat_intervention] ='" & Me.etat.Text & "' "
Your SQL reads like this: where datevisite like '%%'and [Priorité] =''and
Better Solution:
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn.Open()
Dim sql = "SELECT * FROM [maint] where 1=1 "
dt.Clear()
If R1.Checked Then sql = sql & " and datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " and [centr] ='" & Me.centra.Text & "'"
If R3.Checked Then sql = sql & " and [Priorité] ='" & Me.Priorite.Text & "'"
If R4.Checked Then sql = sql & " and [Etat_intervention] ='" & Me.etat.Text & "'"
Dim adapter As New OleDbDataAdapter(sql, MyConn)
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
MyConn.Close()
End Sub
With Parameters:
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim adapter As New OleDbDataAdapter()
Dim command As New OleDbCommand()
Dim sql = "SELECT * FROM [maint] where 1=1 "
Try
MyConn.Open()
dt.Clear()
If R1.Checked Then
sql = sql & " and datevisite like '' "
command.Parameters.AddWithValue("datevisite", "%" & dateintervention.Text & "%")
End If
If R2.Checked Then
sql = sql & " and [centr] = ? "
command.Parameters.AddWithValue("centr", Me.centra.Text)
End If
If R3.Checked Then
sql = sql & " and [Priorité] = ? "
command.Parameters.AddWithValue("Priorité", Me.Priorite.Text)
End If
If R4.Checked Then
sql = sql & " and [Etat_intervention] = ? "
command.Parameters.AddWithValue("Etat_intervention", Me.etat.Text)
End If
command.Connection = MyConn
command.CommandText = sql
adapter.SelectCommand = command
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
Catch exp As Exception
Throw exp
Finally
If MyConn IsNot Nothing Then MyConn.Close()
End Try
End Sub
If R1.Checked is false and R2.Checked is true, then you have no WHERE keyword ... your not building the dynamic SQL statement properly.
Also this is highly susceptible to SQL Injection

how to use multiple combo boxes to filter data

can someone please help me with this problem i'm a beginner in programming.
there is two comboboxes which is S.Y.(school year) and Sem(semester) and i want to use these two combo boxes to have more specific data in the listview below.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT edp_number, LastName + ', ' + FirstName as name, course as course, Address as address, syear as syear, Sem as sem FROM tblStudent"
If Me.cboSearchBy.Text = "1st" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%'"
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
this code only uses the sem combobox which is cboSearchby so now all i need to know is how to make combobox S.Y to function too and if also to use that texbox to search for firstname and lastname.
you just have to add another condition in your If statement:
If Me.cboSearchBy.Text = "1st" and Me.cboSY.Text = "2014-2015" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
End If
then if you want to add the searching for lastname and firstname, just add another condition on the IF-Statement.
Take Note: In using Logical Operator, AND is true if all condition is true while OR is true if atleast one of the conditions is true.

Populate ListView In VB.Net

Code to show the data in two tables display in ListView (CODE WORKS PERFECTLY):
#Region "FillListView"
Sub FillListview()
LV.Items.Clear()
myqry = "SELECT AccResult.StudNo,AccResult.CNumber,AccResult.FirstName,AccResult.LastName,AccResult.YrandSec,Exercises.Exer1,Exercises.Exer2,Exercises.Exer3,Exercises.Exer4,Exercises.Exer5 from AccResult INNER JOIN Exercises ON AccResult.StudNo = Exercises.StudNo ORDER BY AccResult.FirstName,AccResult.YrandSec Asc;"
mycmd = New OleDbCommand(myqry, con)
con.Open()
mydr = mycmd.ExecuteReader
While mydr.Read
With LV
.Items.Add(mydr("StudNo"))
With .Items(.Items.Count - 1).SubItems
.Add(mydr("CNumber"))
.Add(mydr("FirstName"))
.Add(mydr("LastName"))
.Add(mydr("YrandSec"))
.Add(mydr("Exer1"))
.Add(mydr("Exer2"))
.Add(mydr("Exer3"))
.Add(mydr("Exer4"))
.Add(mydr("Exer5"))
End With
End With
End While
con.Close()
End Sub
#End Region
Code for Populate ListView (ERROR):
Public Sub PopulateListView()
Me.LV.Items.Clear()
Dim OleDr As OleDb.OleDbDataReader
OleDr = OleDa.SelectCommand.ExecuteReader() <-----< ERROR: The specified field '[StudNo]' could refer to more than one table listed in the FROM clause of your SQL statement.
Do While OleDr.Read()
Dim Item As New ListViewItem
Item.Text = IIf(OleDr.IsDBNull(0), "", OleDr.Item(0))
For shtCntr = 1 To OleDr.FieldCount() - 1
If Not OleDr.IsDBNull(shtCntr) Then
Item.SubItems.Add(OleDr.Item("CNumber"))
Item.SubItems.Add(OleDr.Item("FirstName"))
Item.SubItems.Add(OleDr.Item("LastName"))
Item.SubItems.Add(OleDr.Item("YrandSec"))
Item.SubItems.Add(OleDr.Item("Exer1"))
Item.SubItems.Add(OleDr.Item("Exer2"))
Item.SubItems.Add(OleDr.Item("Exer3"))
Item.SubItems.Add(OleDr.Item("Exer4"))
Item.SubItems.Add(OleDr.Item("Exer5"))
Else
Item.SubItems.Add("")
End If
Next shtCntr
Me.LV.Items.Add(Item)
Loop
End Sub
Code for Search:
Private Sub BSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BSearch.Click
If txtSearch.Text = "" Then
MsgBox("Please enter keyword to search...", MsgBoxStyle.Information, "Keyword to search...")
txtSearch.Focus()
Exit Sub
End If
Call OpenConnection()
With OleDa
Call Initialized()
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "SELECT * FROM [AccResult],[Exercises] WHERE StudNo Like '%%" & txtSearch.Text & "%%' or [YrandSec] Like '%%" & txtSearch.Text & "%%' or [LastName] Like '%%" & txtSearch.Text & "%%'" & _
"Or [FirstName] Like '%%" & txtSearch.Text & "%%' or [Exer1] Like '%%" & txtSearch.Text & "%%' or [Exer2] Like '%%" & txtSearch.Text & "%%' or [Exer3] Like '%%" & txtSearch.Text & "%%'" & _
"Or [Exer4] Like '%%" & txtSearch.Text & "%%' or [Exer5] Like '%%" & txtSearch.Text & "%%' ORDER By YrandSec, LastName ASC"
.SelectCommand.Connection = OleCn
Call PopulateListView()
If Me.LV.Items.Count >= 1 Then
MsgBox(Me.LV.Items.Count & " Record(s) found for " & "( " & Me.txtSearch.Text & " )", MsgBoxStyle.OkOnly, "Record(s) found...")
Else
MsgBox("No record(s) found for " & "( " & Me.txtSearch.Text & " )" & " , please try again... ", MsgBoxStyle.Critical, "No record found...")
txtSearch.Focus()
txtSearch.SelectAll()
End If
End With
Call CloseConnection()
End Sub
How to populate listview after searching data in two data tables. It gives me error after searching. Thank You in advance.
It seems that both tables AccResult and Exercises contain a field named StudNo and when you refer to that field in the where statement the database cannot decide for you which field you are referring to.
To remove the problem prefix the field name StudNo with the name of the table like you have done in the code that works
Said that, please consider that your query, using string concatenation, is doomed to failure.
If a simple single quote is present in your search term the code will fail with a syntax error.
And then there is the big problem of Sql Injection
With OleDa
Dim searchTerm = "%" & txtSearch.Text & "%"
Call Initialized()
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "SELECT * FROM AccResult INNER JOIN Exercises " & _
"ON AccResult.StudNo = Exercises.StudNo " & _
"WHERE AccResult.StudNo Like ? " & _
"or [YrandSec] Like ? " & _
"or [LastName] Like ? " & _
"Or [FirstName] Like ? " & _
"or [Exer1] Like ? " & _
"or [Exer2] Like ? " & _
"or [Exer3] Like ? " & _
"Or [Exer4] Like ? " & _
"or [Exer5] Like ? " & _
"ORDER By YrandSec, LastName ASC"
.SelectCommand.Parameters.AddWithValue("#p1", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p2", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p3", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p4", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p5", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p6", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p7", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p8", searchTerm)
.SelectCommand.Parameters.AddWithValue("#p9", searchTerm)
.SelectCommand.Connection = OleCn
.......
In this version I have removed the ugly string concatenation and used a parameterized query. The command is more readable and the join of the wildcard char is done just one time. Unfortunately, OleDb cannot recognize the parameters by their names and so we need to add a parameter (#pX) for every placeholder (?) present in the query text