I'm new to vb.net.. so sorry in advance. can anyone help me what's wrong with my elseif line of code.
Dim con As SqlConnection = New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=ordering;User ID=sa;Password=123")
Dim cmd1 As SqlCommand = New SqlCommand("Select * from Customer", con)
Dim first1 As String
Dim second2 As String
first1 = "FirstName"
second2 = "LastName"
con.Open()
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
'this will supposedly display error message for "User Already Exist"
' ElseIf textbox1.text = first1 and textbox2.text = second2 Then
' MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
Dim cmd As SqlCommand = New SqlCommand("Insert into [ordering].[dbo].[Customer] ([FirstName],[LastName]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
TextBox1.Text = ""
TextBox2.Text = ""
con.Close()
End If
You need to actually check to see if the user already exists by executing the SELECT * FROM Customer query, but you need to add the WHERE clause, like this:
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
Else
Dim theQuery As String = "SELECT * FROM Customer WHERE FirstName=@FirstName AND LastName=@LastName"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("@FirstName", TextBox1.Text)
cmd1.Parameters.AddWithValue("@LastName", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
' User does not exist, add them
Dim cmd As SqlCommand = New SqlCommand("Insert into [ordering].[dbo].[Customer] ([FirstName],[LastName]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
TextBox1.Text = ""
TextBox2.Text = ""
End If
End Using
con.Close()
End If
Note: I added the usage of a parameterized query in the
SELECT *query. You should prefer parameterized queries to in-line SQL because it will protect your code from SQL Injection attacks. Never trust the data typed in by the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With