How to stop loop - vb.net

I have a problem with Do until loop. When the record successfully saved and message-box appeared, after clicking the OK button it just shows the message-box and repeat it endlessly. I don't know what's the code for that. Please help.
MySqlConn.Open()
Dim last, midd, first, age, occu, phone As MySqlDataReader
Dim cmd1, cmd2, cmd3, cmd4, cmd5, cmd6, cmd7, cmd8, cmd9, cmd10, cmd11 As New MySqlCommand
Dim query1, query2, query3, query4, query5, query6, query7, query8, query9, query10, query11 As String
'lastname query
query1 = "SELECT * FROM newpatient WHERE Lastname ='" & txtLastname.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
last = cmd1.ExecuteReader
'first query
query2 = "SELECT * FROM newpatient WHERE Firstname ='" & txtFirstname.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
last.Close()
first = cmd2.ExecuteReader
'middle query
query3 = "SELECT * FROM newpatient WHERE Middlename ='" & txtMiddlename.Text & "'"
cmd3 = New MySqlCommand(query3, MySqlConn)
first.Close()
midd = cmd3.ExecuteReader
'age query
query4 = "SELECT * FROM newpatient WHERE Age ='" & txtAge.Text & "'"
cmd4 = New MySqlCommand(query4, MySqlConn)
midd.Close()
age = cmd4.ExecuteReader
'gender query
query5 = "SELECT * FROM newpatient WHERE Occupation ='" & txtOccupation.Text & "'"
cmd5 = New MySqlCommand(query5, MySqlConn)
age.Close()
occu = cmd5.ExecuteReader
'phone query
query6 = "SELECT * FROM newpatient WHERE Mobile_Number ='" & txtMobileNumber.Text & "'"
cmd6 = New MySqlCommand(query6, MySqlConn)
occu.Close()
phone = cmd6.ExecuteReader
Do While last.HasRows = 0 And first.HasRows = 0 And midd.HasRows = 0 And occu.HasRows = 0 And phone.HasRows = 0 And age.HasRows = 0
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO newpatient (ID, Lastname, Firstname, Middlename, Age, Mobile_Number, Gender, Address, Occupation, Month, Day, Year )" &
"VALUES ('{0}' ,'{1}' ,'{2}' ,'{3}' ,'{4}' ,'{5}' , '{6}', '{7}', '{8}', '{9}', '{10}', '{11}' )",
txtID.Text,
txtLastname.Text,
txtFirstname.Text,
txtMiddlename.Text,
txtAge.Text,
txtMobileNumber.Text,
cmbGender.SelectedItem,
txtAddress.Text,
txtOccupation.Text,
cmbMonth.SelectedItem,
cmbDay.SelectedItem,
cmbYear.SelectedItem)
phone.Close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
'AUTO GENERATE RANDOM IDs
Dim random As New Random
Dim id As Integer
id = (random.Next(100000000, 1000000000))
txtID.Text = id
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
Else
MsgBox("Saving record failed.", MsgBoxStyle.Critical, "Failed")
'AUTO GENERATE RANDOM IDs
Dim random As New Random
Dim id As Integer
id = (random.Next(100000000, 1000000000))
txtID.Text = id
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
End If
Loop
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
MsgBox("Patient has already registered!", MsgBoxStyle.Critical, "Already registered")
MySqlConn.close()

To stop the loop requires a call to Exit, like so:
Exit Do
Having said that, you should never just call Exit without requiring a condition to be met, or you can encounter unexpected behavior.
But you've got much larger problems here. I'm going to list them out quickly and include a quick pseudocode suggestion (as in I've never used MySql in .Net, so not at all familiar with the API, so this code WILL need modified before it would work)
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = "INSERT INTO newpatient (ID, Lastname, Firstname, Middlename, Age, Mobile_Number, Gender, Address, Occupation, Month, Day, Year )" &
"VALUES (:ID, :Lastname, :Firstname, :Middlename, :Age, :Mobile_Number, :Gender, :Address, :Occupation, :Month, :Day, :Year)"
cmd.Parameters.Add(new MySqlParameter(":ID", txtID.Text))
cmd.Parameters.Add(new MySqlParameter(":Lastname", txtLastname.Text))
cmd.Parameters.Add(new MySqlParameter(":Firstname", txtFirstname.Text))
cmd.Parameters.Add(new MySqlParameter(":Middlename", txtMiddlename.Text))
cmd.Parameters.Add(new MySqlParameter(":Age", txtAge.Text))
cmd.Parameters.Add(new MySqlParameter(":Mobile_Number", txtMobileNumber.Text))
cmd.Parameters.Add(new MySqlParameter(":Gender", cmbGender.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Address", txtAddress.Text))
cmd.Parameters.Add(new MySqlParameter(":Occupation", txtOccupation.Text))
cmd.Parameters.Add(new MySqlParameter(":Month", cmbMonth.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Day", cmbDay.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Year", cmbYear.SelectedItem))
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows = 1 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
Else
If affectedrows = 0 Then
'Most likely the record already existed, call an update here and if you get 1 result, the record existed and you just saved changes
MsgBox("Patient has already registered!", MsgBoxStyle.Critical, "Already registered")
'You could change the above to a Yes/No question about updating the record and have the result in an if to update the record at the user's discretion.
cmd = MySqlConn.CreateCommand
cmd.CommandText = "UPDATE newpatient " &
"SET Lastname = :Lastname, Firstname = :Firstname, Middlename = :Middlename, Age = :Age, Mobile_Number = :Mobile_Number, " &
" Gender = :Gender, Address = :Address, Occupation = :Occupation, Month = :Month, Day = :Day, Year = :Year " &
"WHERE ID = :ID"
cmd.Parameters.Add(new MySqlParameter(":ID", txtID.Text))
cmd.Parameters.Add(new MySqlParameter(":Lastname", txtLastname.Text))
cmd.Parameters.Add(new MySqlParameter(":Firstname", txtFirstname.Text))
cmd.Parameters.Add(new MySqlParameter(":Middlename", txtMiddlename.Text))
cmd.Parameters.Add(new MySqlParameter(":Age", txtAge.Text))
cmd.Parameters.Add(new MySqlParameter(":Mobile_Number", txtMobileNumber.Text))
cmd.Parameters.Add(new MySqlParameter(":Gender", cmbGender.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Address", txtAddress.Text))
cmd.Parameters.Add(new MySqlParameter(":Occupation", txtOccupation.Text))
cmd.Parameters.Add(new MySqlParameter(":Month", cmbMonth.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Day", cmbDay.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Year", cmbYear.SelectedItem))
affectedrows = cmd.ExecuteNonQuery()
If affectedrows = 1 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Saving record failed.", MsgBoxStyle.Critical, "Failed")
End If
Else
'Should never get here. We covered 0 and 1 in the other two logic branches.
'In this small demo, handling when more than 1 record gets updated is out of scope.
End If
End If
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
MySqlConn.close()
Never build queries from strings where you rely on a user for some of those strings. This leaves you vulnerable to SQL injection attacks (try putting a name with an apostrophe in it in one of the name fields and watch the flurry of errors. Then realize someone with malicious intentions could do serious damage to your database if you don't sanitize your inputs) Always parameterize your queries wherever possible!!
Don't repeat yourself! (AKA the DRY principle) If you find yourself copying/pasting the same block of code from place to place, that means you're doing something wrong. In this case, it was that you got stuck on the idea that you HAD to have a loop, and to make sure you're input fields were cleared, you just copied the code to clear them to 3 different places in the codepath. If you find that you NEED to run the same code repeatedly throughout your programs codepath, then generalize it and put it in a function. Your eyes and the eyes of the next person to read/maintain your code will appreciate it!
You need some more knowledge/experience with SQL, and that's ok, everyone had to start somewhere. In the sample, I removed ALL of your select queries in favor of trying ONE insert query and branching the logic based on the result of that 1 query. Much easier to read/maintain. Also, Identity values should be handle BY your sql instance, not in code. You generally want them used sequentially to avoid collisions and you don't want them modified by/visible to end users. Correcting the properties of the ID column allows removal of the random generation code. Just remember that when you insert into a table with an identity column that you don't need to include the identity column in your INSERT statement (SQL will fill that column for you)

Related

How to Create Buffer in-order to avoid duplication of IN and OUT attendance

Im trying to make an IN and OUT, and Have done the whole program with it's database... Now the last is how do I make a time buffer inorder not to get a duplicate record with the same time.
this is the code that I have done to create the running code... Question is How do I make the buffer. I have search through the internet yet I couldn't find the suitable method
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
status.Text = "IN"
End While
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
If (dr("entry_record")) = "IN" Then
record = "OUT"
ElseIf (dr("entry_record")) = "OUT" Then
record = "IN"
ElseIf (dr("entry_record")) = String.Empty Then
record = "IN"
End If
status.Text = (record)
End While
dr.Close()
cn.Close()
ConnectToDB()
sql = "insert into monitoring (id_num, fname, lname, status, entry_record, floor_level, date) VALUES (#num, #name, #lname, #stat, #record, #lev,#date)"
cmd = New MySqlCommand(sql, cn)
With cmd
.Parameters.AddWithValue("#num", idnum)
.Parameters.AddWithValue("#name", TextBox2.Text)
.Parameters.AddWithValue("#lname", TextBox6.Text)
.Parameters.AddWithValue("#stat", TextBox5.Text)
.Parameters.AddWithValue("#lev", levellock.sharevalue)
.Parameters.AddWithValue("#record", status.Text)
.Parameters.AddWithValue("#date", Date.Now)
.ExecuteReader()
End With
MsgBox("Details has been saved!", vbInformation, "Saved")
cmd = Nothing
dr.Close()
cn.Close()
I don't know if this what you meant because your english is horrible.
How about in the Date.Now you also include second so it become like this
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
y = Year
M = Month
d = Date
H = Hour
m = Minute
s = Second

How solve this problem syntax error in UPDATE statement

This problem at syntax error for update statement then I don't know how to solve this problem
Private Sub editStaff()
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
If IDTextBox.Text <> "" And FirstTextBox.Text <> "" And SecondTextBox.Text <> "" And UsernameTextBox.Text <> "" And PasswordTextBox.Text <> "" Then
strSQL = "update Staff set First_Name = '" & FirstTextBox.Text & "', " &
"Second_Name = '" & SecondTextBox.Text & "', " & "Username = '" & UsernameTextBox.Text & "', " &
"Password = '" & PasswordTextBox.Text & "'" & " where ID = " & CInt(IDTextBox.Text) & ""
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
For some reason your validation If did not include the ID text box. I added validation for this text box. The OrElse is a short circuit. As soon as it finds a True it stops checking the conditions and proceeds to the next line.
This code
If con.State = ConnectionState.Closed Then
con.Open()
End If
is completely unnecessary if you keep your database objects local. Keeping them local allows you to ensure they are closed and disposed with Using...End Using blocks.
Don't open the connection until you need it which is directly before the .Execute... line. Use parameters to avoid Sql Injection. Also your Update statement is much easier to write without all the single quotes and double quotes and ampersands.
Caution In Access the order that the parameters appear in the Sql statement must match the order that they are added to the .Parameters collection.
Finally, you should NEVER store passwords as plain text. I will leave it to you to research salting and hashing and correct the code.
Private Sub editStaff()
Dim i As Integer
If Integer.TryParse(IDTextBox.Text, i) Then
MessageBox.Show("ID text box must be a number")
Return
End If
If IDTextBox.Text = "" OrElse FirstTextBox.Text = "" OrElse SecondTextBox.Text = "" OrElse UsernameTextBox.Text = "" OrElse PasswordTextBox.Text = "" Then
MessageBox.Show("Please fill in all text boxes")
Return
End If
Try
Using con As New OleDbConnection("Your connection string")
Dim strSQL = "Update Staff set First_Name = #FirstName, Second_Name = #SecondName, [Username] = #UserName, [Password] = #Password Where [ID] = #ID"
Using cmd As New OleDbCommand(strSQL, con)
With cmd.Parameters
.Add("#FirstName", OleDbType.VarChar).Value = FirstTextBox.Text
.Add("#SecondName", OleDbType.VarChar).Value = SecondTextBox.Text
.Add("#UserName", OleDbType.VarChar).Value = UsernameBox.Text
.Add("#Password", OleDbType.VarChar).Value = PasswordTextBox.Text
.Add("#ID", OleDbType.Integer).Value = CInt(IDTextBox.Text)
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

autofilling textboxes with database data based on a primary key entry into another textbox

i have the code below, it works fine but whenever i insert a student number that does not exist in the table, the rest of the textboxes will keep displaying data from the previous existing entry. This happens even when the i delete everything in the student number textbox.
how can i change it such that the rest of the textboxes are cleared in case the student number textbox is blank or contains a student number that does not exist in the database?
Thanks in advance.
' Try
Dim mycommand As SqlCommand = New SqlCommand()
Dim datareader As SqlDataReader = Nothing
myconnection.Open()
Dim query As String
query = " select StudentNo,Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "' and (class = 'Senior 5A' or Class ='Senior 5S' or Class='Senior 6A' or class='Senior1 6S')"
mycommand = New SqlCommand(query, myconnection)
datareader = mycommand.ExecuteReader()
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
End If
End While
myconnection.Close()
' Catch ex As Exception
'MessageBox.Show(ex.Message)
' End Try`
Add an else condition to reader and clear text boxes in that module.
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
else
TxtName.Text = ""
TxtYear.Text = ""
TxtTerm.Text = ""
TxtClass.Text = ""
End If
hope theres no big deal more than this.
I finally changed my code to the one below and it's doing exactly what i want.
Private Sub getData()
Dim dt As New DataTable()
myconnection.Open()
Dim Mycommand As New SqlCommand("select Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "'", myconnection)
Dim sqlDa As New SqlDataAdapter(Mycommand)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TxtName.Text = dt.Rows(0)("FullName").ToString()
TxtYear.Text = dt.Rows(0)("Year").ToString()
Else
TxtName.Text = ""
TxtYear.Text = ""
End If
myconnection.Close()
End Sub

Why do I get "Syntax error in INSERT INTO statement"?

Private Sub Save_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandText = CommandType.Text
If Me.txt_Forename.Tag = 0 Then
sSQL = "INSERT INTO PlayerDatabase ( Age_Group, Surname, Forename, Rating, DOB, Address, Email, Position, Foot, Mins_Played, Goals, Assists, Yellow_Cards, Red_Cards)"
sSQL = sSQL & " VALUES(#Age_Group, #Surname, #Forename, #Rating, #DOB, #Address, #Email, #Position, #Foot, #Mins_Played, #Goals, #Assists, #Yellow_Cards, #Red_Cards)"
Else
sSQL = "UPDATE PlayerDatabase set Age_Group = #Age_Group, Surname = #Surname, Forename = #Forename, Rating = #Rating, DOB = #DOB, Address = #Address, Email = #Email, Position = #Position, Foot = #Foot, Mins_Played = #Mins_Played, Goals = #Goals, Assists = #Assists, Yellow_Cards = #Yellow_Cards, Red_Cards = #Red_Cards WHERE ID = #id"
cmd.CommandText = sSQL
End If
cmd.Parameters.Add("#Surname", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Surname.Text)) > 0, Me.txt_Surname.Text, DBNull.Value)
cmd.Parameters.Add("#Forename", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Forename.Text)) > 0, Me.txt_Forename.Text, DBNull.Value)
cmd.Parameters.Add("#DOB", OleDbType.Date).Value = Me.dtp_DOB.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = Me.txt_Address.Text
cmd.Parameters.Add("#Age_Group", OleDbType.VarChar).Value = Me.cb_AgeGroup.Text
cmd.Parameters.Add("#Rating", OleDbType.VarChar).Value = Me.cb_Rating.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = Me.txt_Email.Text
cmd.Parameters.Add("#Position", OleDbType.VarChar).Value = Me.cb_Position.Text
cmd.Parameters.Add("#Foot", OleDbType.VarChar).Value = Me.cb_Foot.Text
cmd.Parameters.Add("#Mins_Played", OleDbType.VarChar).Value = Me.nup_MinsPlayed.Text
cmd.Parameters.Add("#Goals", OleDbType.VarChar).Value = Me.nup_Goals.Text
cmd.Parameters.Add("#Assists", OleDbType.VarChar).Value = Me.nup_Assists.Text
cmd.Parameters.Add("#Yellow_Cards", OleDbType.VarChar).Value = Me.nup_YellowCards.Text
cmd.Parameters.Add("#Red_Cards", OleDbType.VarChar).Value = Me.nup_RedCards.Text
cmd.Parameters.Add("#ID", OleDbType.Numeric).Value = Me.txt_Forename.Tag
cmd.ExecuteNonQuery()
If Me.txt_Forename.Tag = 0 Then
cmd.CommandText = "Select ##Identity"
Me.txt_Forename.Tag = cmd.ExecuteScalar()
End If
MsgBox("Data has been saved.")
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
Not sure what I'm doing wrong here. This is a adding to an Access database from various textboxes, comboboxes etc. This procedure runs when a button is pressed on a form that has the inputs. I'm a beginner at vb.net and programming in general so if it's something obvious I apologise.
Thanks
The word POSITION is reserved in MS-Access Jet Sql. This is the reason of the SYNTAX ERROR.
If you want to use it as a name for a column or for a table you need to put it between square brackets
sSQL = "INSERT INTO PlayerDatabase ( Age_Group, Surname, Forename, Rating, DOB, " & _
"Address, Email, [Position], Foot, Mins_Played, Goals, Assists, Yellow_Cards, Red_Cards)"
....
sSQL = "UPDATE PlayerDatabase set Age_Group = #Age_Group, Surname = #Surname, " & _
"Forename = #Forename, Rating = #Rating, DOB = #DOB, Address = #Address, " & _
"Email = #Email, [Position] = #Position, Foot = #Foot, Mins_Played = #Mins_Played, " & _
"Goals = #Goals, Assists = #Assists, Yellow_Cards = #Yellow_Cards, " & _
"Red_Cards = #Red_Cards WHERE ID = #id"
A part from this you have another problem. OleDb doesn't recognize the parameters by their names. Usually you should use a question mark instead of a name, but Access allows this probably for some kind of portability toward its big cousin Sql Server. In any case you should add the parameters in the OleDbCommand collection in the same order in which the named placeholders appears in your query. So you need this order:
cmd.Parameters.Add("#Age_Group", OleDbType.VarChar).Value = Me.cb_AgeGroup.Text
cmd.Parameters.Add("#Surname", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Surname.Text)) > 0, Me.txt_Surname.Text, DBNull.Value)
cmd.Parameters.Add("#Forename", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Forename.Text)) > 0, Me.txt_Forename.Text, DBNull.Value)
cmd.Parameters.Add("#Rating", OleDbType.VarChar).Value = Me.cb_Rating.Text
cmd.Parameters.Add("#DOB", OleDbType.Date).Value = Me.dtp_DOB.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = Me.txt_Address.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = Me.txt_Email.Text
cmd.Parameters.Add("#Position", OleDbType.VarChar).Value = Me.cb_Position.Text
cmd.Parameters.Add("#Foot", OleDbType.VarChar).Value = Me.cb_Foot.Text
cmd.Parameters.Add("#Mins_Played", OleDbType.VarChar).Value = Me.nup_MinsPlayed.Text
cmd.Parameters.Add("#Goals", OleDbType.VarChar).Value = Me.nup_Goals.Text
cmd.Parameters.Add("#Assists", OleDbType.VarChar).Value = Me.nup_Assists.Text
cmd.Parameters.Add("#Yellow_Cards", OleDbType.VarChar).Value = Me.nup_YellowCards.Text
cmd.Parameters.Add("#Red_Cards", OleDbType.VarChar).Value = Me.nup_RedCards.Text
and this last parameter should be added only if you have the UPDATE path not for the INSERT. (Assuming the ID column to be an AutoIncrement one)
If Me.txt_Forename.Tag <> 0 Then
cmd.Parameters.Add("#ID", OleDbType.Numeric).Value = Me.txt_Forename.Tag
End If
Also another problem at the end when you try to read the ##IDENTITY value. Using the same command is fine, but you need to clear the parameters collection
If Me.txt_Forename.Tag = 0 Then
cmd.Parameters.Clear()
cmd.CommandText = "Select ##Identity"
Me.txt_Forename.Tag = cmd.ExecuteScalar()
End If

SQL to search for encrypted values not working

I am using a button to trigger a SELECT statement, and based off of the criteria the user enters in 2 text boxes (SearchFirstTxt, SearchLastTxt), I send the Text values of those text boxes through an encryption class to find their match
I return them in a SqlDataAdapter and use it to fill a DataTable. I then use DataGridView.DataSoruce = dt to add it to the DGV.
My question: If the user leaves both text boxes blank and clicks the "SearchBtn", it doesn't select all of the records. It actually only selects records with the same encrypted values.
Here is the code:
eFirst = clsEncrypt.EncryptData(SearchFirstTxt.Text.Trim.ToUpper)
eLast = clsEncrypt.EncryptData(SearchLastTxt.Text.Trim.ToUpper)
conn.Open()
cmd.Connection = conn
If SearchFirstTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = '" & eLast & "' ; "
ElseIf SearchLastTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = '" & eFirst & "' ; "
Else
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
End If
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
DataGridView1.DataSource = dt
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(eFirst)
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(eLast)
Next
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try
How can I select ALL of the records from the Participant dbo?
The result set looks like this if the text boxes are left blank:
Edit: I switched my code, and it retrieves ALL of the results, however, now I am having difficulty returning them. (They return as encrypted, but not decrypted)
Here are the changes:
If SearchFirstTxt.Text = "" And SearchLastTxt.Text = "" Then
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
ElseIf SearchLastTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = '" & eFirst & "' ; "
ElseIf SearchFirstTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = '" & eLast & "' ; "
End If
If I understand your requirements correctly, you need to add a check for the other search text when you try to search your encrypted data
If SearchFirstTxt.Text = "" AndAlso SearchLastTxt.Text <> "" Then
' Search the last only if you have a last and not a first'
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = #searchLast"
cmd.Parameters.AddWithValue("#searchLast", eLast)
ElseIf SearchLastTxt.Text = "" AndAlso SearchFirstTxt.Text <> "" Then
' Search the first only if you have a first and not a last'
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = #searchFirst"
cmd.Parameters.AddWithValue("#searchFirst", eFirst)
ElseIf SearchFirstTxt.Text = "" AndAlso SearchLastText.Text = "" Then
' Both emtpy so search everything'
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
Else
' Both filled so search exactly (not sure if this is needed)'
cmd.CommandText = "Select * FROM Participant " & _
"WHERE FIRST_NM_TXT = #searchFirst " & _
"OR LAST_NM_TXT = #searchLast"
cmd.Parameters.AddWithValue("#searchFirst", eFirst)
cmd.Parameters.AddWithValue("#searchLast", eLast)
End If
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
Notice that I have removed your string concatenation and used a parameterized query. It is safer (avoids Sql Injection) and remove parsing problems (what if your encrypted text contains a single quote?)
Supposing then that you want to show the decrypted data you apply your deCryptData function to the values in the datatable, not to the same values used for the search (you already know the clear text)
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("FIRST_NM_TXT").ToString)
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("LAST_NM_TXT").ToString)
Next
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try