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(\
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.