VB.net search button - sql

I was working on this search button and I've manage to make it work. The only down side to this is when I try to search for a different item it keeps on putting back the old one I've searched for. What could be the problem?
Here's the code:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
com.Connection = con
com.CommandText = ("Select Student_ID from Student where Student_ID = '" & txtSearch.Text & "'")
com.CommandText = "SELECT * FROM Student"
OpenDB()
Dim SurName As String = ""
Dim MiddleName As String = ""
Dim FirstName As String = ""
Dim SAddress As String = ""
Dim Birthday As String = ""
Dim Age As String = ""
Dim Birthplace As String = ""
Dim SContactNumber As String = ""
Dim GradeYear As String = ""
Dim SchoolYear As String = ""
Dim ParentGaurdian As String = ""
Dim PGContact As String = ""
Dim PGAddress As String = ""
rdr = com.ExecuteReader
If rdr.Read = True Then
SurName = rdr("StudentLastName").ToString
MiddleName = rdr("StudentMiddleName").ToString
FirstName = rdr("StudentFirstName").ToString
SAddress = rdr("StudentAddress").ToString
Birthday = rdr("Birthday").ToString
Age = rdr("Age").ToString
Birthplace = rdr("BirthPlace").ToString
SContactNumber = rdr("StudentContactNumber").ToString
GradeYear = rdr("GradeYearLevel").ToString
SchoolYear = rdr("SchoolYear").ToString
ParentGaurdian = rdr("ParentName").ToString
PGContact = rdr("ParentContactNumber").ToString
PGAddress = rdr("ParentAddress").ToString
End If
con.Close()
com.Dispose()
rdr.Close()
txtSurName.Text = SurName
txtMiddleName.Text = MiddleName
txtFirstName.Text = FirstName
txtSAddress.Text = SAddress
txtBirthday.Text = Birthday
txtAge.Text = Age
txtBirthplace.Text = Birthplace
txtSContactNumber.Text = SContactNumber
txtGradeYear.Text = GradeYear
txtSchoolYear.Text = SchoolYear
txtParentGaurdian.Text = ParentGaurdian
txtPGContact.Text = PGContact
txtPGAddress.Text = PGAddress
End Sub
I've tried to play around with the rdr.close because I think that's the thing I've placed wrong.

Looks like your SQL query should be more like this:
'com.CommandText = ("Select Student_ID from Student where Student_ID = '" & txtSearch.Text & "'")
'com.CommandText = "SELECT * FROM Student"
com.CommandText = "SELECT * FROM Student WHERE Student_ID = '" & txtSearch.Text & "'"

Remove below two lines..
com.CommandText = ("Select Student_ID from Student where Student_ID = '" & txtSearch.Text & "'")
com.CommandText = "SELECT * FROM Student"
And instead use below..
com.CommandText = ("Select Student_ID from Student where Student_ID = #searchText")
com.Parameters.AddWithValue("#searchText", txtSearch.Text)

Related

Multiselection in vb.net ListBox

I have a list of student names in a listBox,(studentList)I click on a name in the box and get all the students details up ie name, course, subject etc.The code then gets the details from the database(in my case it's access) then displays it in a datagridview.
The code works fine if I just select one item from one(or all)List Boxes.My question is, can I select more than one item per LitsBox.I know I can use SelectedMode property to allow the highlighting but that wont draw the required data from the database.Here is the code I am using vb.10
`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
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim isFirstColumn As Boolean = True
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim x As String = studentList.Text
Dim y As String = courseList.Text
Dim z As String = gradeList.Text
Dim defaultSQL As String = "SELECT * FROM studentfile "
If studentList.SelectedIndex > -1 Then
If isFirstColumn Then
student = "WHERE student = '" & x & "' "
Else
student = "AND student = '" & x & "' "
End If
isFirstColumn = False
End If
If courseList.SelectedIndex > -1 Then
If isFirstColumn Then
course = "WHERE course = '" & y & "' "
Else
course = "AND course = '" & y & "' "
End If
isFirstColumn = False
End If
If gradeList.SelectedIndex > -1 Then
If isFirstColumn Then
grade = "WHERE grade = '" & z & "' "
Else
grade = "AND grade = '" & z & "' "
End If
isFirstColumn = False
End If
Dim sql As String = defaultSQL & student & course & grade
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub`
many thanks
grey
Using the .SelectedItems (and a lot of jiggery with the where clause.... you should be able to use this to EITHER have multi-select of single select accross all three listboxes as well as not selecting anything from any of them too...
The only question I would have would be whether you want all the 'AND's as this would mean if you selected two students, you wouldnt get any results... as no two students are the same right? Unless you selected two 'Dave's in which it would return both. For example!
Might suggest changing some for 'OR's or look at what the end result might be? Either way comment and let us know if need any further help
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
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim defaultSQL As String = "SELECT * FROM studentfile "
Dim WhereClause As String = ""
Dim StudentCourseGrade As String
'Students---------------------------------------------
For Each stu In studentList.SelectedItems
StudentCourseGrade = "(student='" & stu & "'"
For Each crs In courselist.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND course = '" & crs & "'"
For Each grd In gradeList.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND grade = '" & crs & "'"
Next
Next
StudentCourseGrade = StudentCourseGrade & ")"
If WhereClause.Length = 0 Then
WhereClause = "WHERE " & StudentCourseGrade
Else
WhereClause = " OR " & StudentCourseGrade
End If
Next
'Students---------------------------------------------
Dim SQL As String = defaultSQL & WhereClause
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub
Hth
Chicken

VB NET - Select * From issue

I have some wierd exception.
I have Access database with 2 tables, one named MYSB_DB and the other Employee.
I'm using the code below when I want to filter on something like that:
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String = String.Empty '
Dim pName As String = String.Empty
Dim fName As String = String.Empty
Dim ColpName As String = String.Empty
Dim ColfName As String = String.Empty
Dim ch As Integer = InStr(1, cmbEmployees.Text, " ", CompareMethod.Text)
pName = cmbEmployees.Text.Substring(0, ch)
fName = cmbEmployees.Text.Substring(ch, cmbEmployees.Text.Length - ch)
ColpName = "שדה1"
ColfName = "שדה2"
sql = "SELECT * FROM Employee WHERE [" & ColpName & "]=" & pName & ";"
da = New OleDb.OleDbDataAdapter(sql, Me.EmployeeTableAdapter.Connection.ConnectionString)
da.Fill(ds, Me.MYSB_DataBaseDataSet1.Employee.TableName)
I only change between the tables name in the code.
When I'm using this code for MYSB_DB table, the code is running well, but when I'm using the code for Employee table, I have an exception.
Any ideas why it's happening?
pName is a string, so it must be quoted:
sql = "SELECT * FROM Employee WHERE [" & ColpName & "]='" & pName & "';"

Syntax error in update query in VB .NET

I'm trying to run a SQL command in VB .NET but it returns a error message of syntax error in my string variable which I just not able to figure out by myself since this is my first experience for programming with SQL command.The specific message is:
Syntax error (missing operator) in query express '= '045617123'.
Where "045617123" is the data stored in one of the data fields
Can someone please help me out from this? Thank You
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim conobj As New OleDb.OleDbConnection(constr)
Dim da1 As New OleDb.OleDbDataAdapter()
Dim da2 As New OleDb.OleDbDataAdapter()
Dim sqlstr1 As String = ""
Dim sqlstr2 As String = ""
conobj.Open()
For i As Integer = 0 To vt1.Rows.Count - 1
sqlstr1 = "UPDATE Students SET LastName = '" & vt1.Rows(i)(1) & "', FirstName = '" & vt1.Rows(i)(2) & "', StreetAddress = '" & vt1.Rows(i)(3) & "', City = '" & vt1.Rows(i)(4) & "', State = '" & vt1.Rows(i)(5) & "', ZipCode = '" & vt1.Rows(i)(6) & "' WHERE = '" & vt1.Rows(i)(0) & "'"
da1.UpdateCommand = New OleDb.OleDbCommand(sqlstr1, conobj)
da1.UpdateCommand.ExecuteNonQuery()
Next
'For i As Integer = 0 To vt2.Rows.Count - 1
'sqlstr2 = "UPDATE Grades SET FirstExam = " & vt2.Rows(i)(1) & ", SecondExam = " & vt2.Rows(i)(2) & ", FinalExam = " & vt2.Rows(i)(3) & "WHERE StID = " & vt1.Rows(i)(0)
'da2.UpdateCommand = New OleDb.OleDbCommand(sqlstr2, conobj)
'da2.UpdateCommand.ExecuteNonQuery()
'Next
conobj.Close()
End Sub
Use SqlParameters. If some of your datafields contain ' charachter then sql query return a syntax error. Or users can create a Sql injection query.
Your syntax error in the WHERE = '" & vt1.Rows(i)(0) & "'" There are no column name which must be same as datafield value
Here example of using parameters:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim query as New StringBuilder()
With query
.AppendLine("UPDATE Students SET LastName = #LastName")
.AppendLine(", FirstName = #FirstName")
.AppendLine(", StreetAddress = #StreetAddress")
.AppendLine(", City = #City")
.AppendLine(", State = #State")
.AppendLine(", ZipCode = #ZipCode")
.AppendLine("WHERE YourIDField = #ID;")
End With
Using conobj As New OleDb.OleDbConnection(constr)
conobj.Open()
Dim da1 As New OleDb.OleDbDataAdapter()
For i As Integer = 0 To vt1.Rows.Count - 1
Using updCommand As New OleDb.OleDbCommand(query.ToString(), New OleDb.OleDbConnection(""))
updCommand.Parameters.AddWithValue("#LastName", vt1.Rows(i)(1))
updCommand.Parameters.AddWithValue("#FirstName ", vt1.Rows(i)(2))
updCommand.Parameters.AddWithValue("#StreetAddress ", vt1.Rows(i)(3))
updCommand.Parameters.AddWithValue("#City ", vt1.Rows(i)(4))
updCommand.Parameters.AddWithValue("#State ", vt1.Rows(i)(5))
updCommand.Parameters.AddWithValue("#ZipCode", vt1.Rows(i)(6))
updCommand.Parameters.AddWithValue("#ID", vt1.Rows(i)(0))
da1.UpdateCommand = updCommand
da1.UpdateCommand.ExecuteNonQuery()
End Using
Next
End Using
End Sub

EXTRACT query in Vb.net using sql

This is my code then the problem is it will not show the information in the gridlist. I want to make inner join of my two tables but it doesn't work with my codes. What will be the alternative way of this? Thank you so much for answering.
Dim sqlQuery As String = "SELECT Persons.pr_id, Persons.pr_fname, Persons.pr_mname, Persons.pr_lname, Persons.pr_address, Users.UserName, Users.phone_num FROM Persons" & _
"INNER JOIN Users ON Persons.pr_id = Users.pr_id" & _
" WHERE pr_id='" & TextBox1.Text & "'"
Dim table As New DataTable
cn.Close()
cn.Open()
With cmd
.CommandText = sqlQuery
.Connection = cn
End With
With cmd
.CommandText = sqlQueryUser
.Connection = cn
End With
With sqla
.SelectCommand = cmd
.Fill(table)
End With
If ListView1.SelectedItems.Count > 0 Then
'Button20.Visible = True
'Button10.Visible = True
'RichTextBox2.Enabled = False
'senbyCombo.Enabled = False
'group_sendCombo.Enabled = False
'title.Enabled = False
'ListView3.Enabled = True
id = ListView1.SelectedItems(0).Text
TextBox1.Text = ListView1.SelectedItems(0).SubItems(0).Text
TextBox2.Text = ListView1.SelectedItems(0).SubItems(1).Text
TextBox3.Text = ListView1.SelectedItems(0).SubItems(2).Text
TextBox4.Text = ListView1.SelectedItems(0).SubItems(3).Text
TextBox5.Text = ListView1.SelectedItems(0).SubItems(4).Text
TextBox7.Text = ListView1.SelectedItems(0).SubItems(6).Text
End If
cn.Close()
your pr_id is ambiguous change your query like this :
Dim sqlQuery As String = "SELECT Persons.pr_id, Persons.pr_fname, Persons.pr_mname, Persons.pr_lname, Persons.pr_address, Users.UserName, Users.phone_num FROM Persons" & _
"INNER JOIN Users ON Persons.pr_id = Users.pr_id" & _
" WHERE Persons.pr_id='" & TextBox1.Text & "'"

What is wrong with my vb.net webmethod?

This webmethod retrieves plist, firstaname, lastname, orgid from database then insert 2 lines in 2 different tables. 1st sql is fine - 2nd doesnt run
<WebMethod()> _
Public Function Register(ByVal meetingid As String, ByVal myid As String, ByVal PartType As Integer, ByVal startDate As String) As String
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("EPBconnection").ConnectionString)
Dim sSQL As String
Dim plistid As String = ""
Dim LastName As String = ""
Dim FirstName As String = ""
Dim orgID As String = ""
'get plistID
sSQL = "select pl.PLIST_ID"
sSQL = sSQL + " From PERSON_LIST pl"
sSQL = sSQL + " Where MTG_ID = '" + meetingid + "'"
Dim myCommand As New SqlCommand(sSQL, connection)
connection.Open()
Dim myReader As SqlDataReader = myCommand.ExecuteReader
While myReader.Read()
plistid = myReader("PLIST_ID").ToString()
End While
connection.Close()
'get firstname, lastname, orgid
sSQL = "SELECT p.LASTNAME, p.FIRSTNAME, p.ORGA_ID FROM PERSON p WHERE PERSON_ID = '" + myid + "'"
myCommand = New SqlCommand(sSQL, connection)
connection.Open()
myReader = myCommand.ExecuteReader
While myReader.Read()
LastName = myReader("LASTNAME").ToString()
FirstName = myReader("FIRSTNAME").ToString()
orgID = myReader("ORGA_ID").ToString()
End While
connection.Close()
Return "You are registered for this meeting"
End Function
When i remove the following it returns the string but otherwise it doesnt (compiles without errors either way):
While myReader.Read()
LastName = myReader("LASTNAME").ToString()
FirstName = myReader("FIRSTNAME").ToString()
orgID = myReader("ORGA_ID").ToString()
End While
The problem seems to be coming from myReader.Read()??? I dont understand why
orgID = myReader("ORGA_ID").ToString()
You have defined orgId as Integer;
Dim orgID As Integer
Sorry every1 the problem was solved by itself over night. Still dont know what the problem was. LOL