Populate ListView In VB.Net - 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

Related

filter button syntax error during execution

I have a text box and a filter button to filter the record in my data-grid box , but apparently it is not working and showing error message as
An Error Occured: Syntax error: Missing operand after "%h%" operator.
And this is my code , please help me how to solve this:
Private Sub AlertWarningMessage()
'Do not allow search while addign record
MsgBox("The Search Function Is Disabled While Adding New Record",
MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Find Record")
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
ToolStripStatusLabel1.Text = "Status"
If IsAddNewRecordInProgress = True Then
AlertWarningMessage()
Exit Sub
End If
If Not String.IsNullOrEmpty(KeywordTextBox.Text) Then
SearchInAccessDatabase(KeywordTextBox.Text.Replace("'", "''"))
Else
RefreshData()
Return
End If
End Sub
Private Sub SearchInAccessDatabase(ByVal stringKeyword As String,
Optional stringFilter As String = "")
Try
stringFilter = "(Convert(ID, 'System.String') LIKE '" & stringKeyword & "')" &
" OR ([Size in mg] LIKE '%" & stringKeyword & "%')" &
" OR ([Die head number] LIKE '%" & stringKeyword & "%')" &
" OR (Observations '%" & stringKeyword & "%')" &
" OR (Inspector LIKE '%" & stringKeyword & "%')"
MSdiesBindingSource.Filter = stringFilter
If MSdiesBindingSource.Count < 1 Then
MsgBox("-->>" & stringKeyword & "<<--" & vbNewLine & Environment.NewLine &
"The serach item not found", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
"Find Record")
RefreshData()
End If
Catch ex As Exception
MessageBox.Show("An Error Occured: " & ex.Message.ToString(),
"Find Record", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
In the line
OR (Observations '%" & stringKeyword & "%')"
you are missing the LIKE keyword.
It should be
OR (Observations LIKE '%" & stringKeyword & "%')"
and because of the optional stringFilter parameter, the filter should be set internally only if this parameter has not been passed.
Also, you can simplify the string construction in two ways:
You can use string interpolation. For this, introduce the string with a $. In the string you can specify expressions to be inserted within curly braces.
You can use a multiline string. In VB, this works automatically. If a string is not ended on a line, it is automatically assumed that it continues on the next one.
Private Sub SearchInAccessDatabase(ByVal stringKeyword As String,
Optional stringFilter As String = "")
Try
If stringFilter = "" Then
stringFilter = $"(Convert(ID, 'System.String') LIKE '{stringKeyword}')
OR (Observations LIKE '%{stringKeyword}%')
OR (Inspector LIKE '%{stringKeyword}%')"
Dim number As Double
If Double.TryParse(stringKeyword, number) Then
stringFilter += $" OR ([Size in mg] = {stringKeyword})
OR ([Die head number] = {stringKeyword})"
End If
End If
MSdiesBindingSource.Filter = stringFilter
If MSdiesBindingSource.Count < 1 Then
MsgBox($"-->>{stringKeyword}<<--{vbNewLine}{Environment.NewLine}The serach item not found",
MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
"Find Record")
RefreshData()
End If
Catch ex As Exception
MessageBox.Show($"An Error Occured: {ex.Message}",
"Find Record", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
But it depends how you want to filter these two columns. If you want to filter by the start of the number, for instance, then convert the column to a string and go with LIKE '{stringKeyword}%'.
The same considerations apply to ID. Maybe ID = {stringKeyword} is sufficient if the stringKeyword is an Integer or a Double (it depends on the type of ID.

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.)

Object reference not set to an instance of an object VB.Net OleDbCommand

Everytime i search on my database it always says "Object reference not set to an instance of an object."
Please anyone help me. Thank you.
Here is my code for Search:
Private Sub BtnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSearch.Click
If TBSearch.Text = "" Then
MsgBox("Please enter keyword to search...", MsgBoxStyle.Information, "Keyword to search...")`
TBSearch.Focus()
Exit Sub
End If
Call OpenConnection()
With OleDa
Call Initialized()
.SelectCommand = New OleDb.OleDbCommand() <-------- Error appears here.
.SelectCommand.CommandText = "SELECT * FROM [HighSchool] WHERE [LastName] Like '%%" & TBSearch.Text & "%%' or [FirstName] Like '%%" & TBSearch.Text & "%%' or [MI] Like '%%" & TBSearch.Text & "%%'" & _
"Or [Gender] Like '%%" & TBSearch.Text & "%%' or [Address] Like '%%" & TBSearch.Text & "%%' or [Birthday] Like '%%" & TBSearch.Text & "%%' or [RNumber] Like '%%" & TBSearch.Text & "%%'" & _
"Or [ENumber] Like '%%" & TBSearch.Text & "%%' ORDER By LastName ASC"
.SelectCommand.Connection = OleCn
Call PopulateListView()
If Me.LV.Items.Count >= 1 Then
MsgBox(Me.LV.Items.Count & " Record(s) found for " & "( " & Me.TBSearch.Text & " )", MsgBoxStyle.OkOnly, "Record(s) found...")
Else
MsgBox("No record(s) found for " & "( " & Me.TBSearch.Text & " )" & " , please try again... ", MsgBoxStyle.Critical, "No record found...")
TBSearch.Focus()
TBSearch.SelectAll()
End If
End With
Call CloseConnection()
End Sub
Here is my code for Populate ListView:
Public Sub PopulateListView()
Me.LV.Items.Clear()
Dim OleDr As OleDb.OleDbDataReader
OleDr = OleDa.SelectCommand.ExecuteReader()
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("FirstName"))
Item.SubItems.Add(OleDr.Item("LastName"))
Item.SubItems.Add(OleDr.Item("MI"))
Item.SubItems.Add(OleDr.Item("Gender"))
Item.SubItems.Add(OleDr.Item("Address"))
Item.SubItems.Add(OleDr.Item("Birthday"))
Item.SubItems.Add(OleDr.Item("RNumber"))
Item.SubItems.Add(OleDr.Item("ENumber"))
Else
Item.SubItems.Add("")
End If
Next shtCntr
Me.LV.Items.Add(Item)
Loop
End Sub
Ok, let's fix some stuff.
Don't use Call. That's just a hold-over from VB 6 (i.e. the late 90's)
Don' use Exit Sub. Use Return instead. (Same reason as #1)
Use parameterized SQL rather that string concatenation. Your code, as is, won't work is someone searches for "O'Mally".
Private Sub BtnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSearch.Click
If TBSearch.Text = "" Then
MsgBox("Please enter keyword to search...", MsgBoxStyle.Information, "Keyword to search...")`
TBSearch.Focus()
Exit Sub
End If
Call OpenConnection()
With OleDa
Call Initialized()
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "SELECT * FROM [HighSchool] WHERE [LastName] Like #TBSearch or [FirstName] Like #TBSearch or [MI] Like #TBSearch Or [Gender] Like #TBSearch or [Address] Like #TBSearch or [Birthday] Like #TBSearch or [RNumber] Like #TBSearch Or [ENumber] Like #TBSearch ORDER By LastName ASC"
.SelectCommand.Connection = OleCn
.SelectCommand.Parameters.AddWithValue("#TBSearch", "%" & TBSearch.Text & "%")
Call PopulateListView()
If Me.LV.Items.Count >= 1 Then
MsgBox(Me.LV.Items.Count & " Record(s) found for " & "( " & Me.TBSearch.Text & " )", MsgBoxStyle.OkOnly, "Record(s) found...")
Else
MsgBox("No record(s) found for " & "( " & Me.TBSearch.Text & " )" & " , please try again... ", MsgBoxStyle.Critical, "No record found...")
TBSearch.Focus()
TBSearch.SelectAll()
End If
End With
Call CloseConnection()
End Sub
As for your error, the only possible cause is that OleDa is Nothing.

Searching a database with a ComboBox

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.