How to check the exist value
Using VB.Net and Sql Server
I want to check the user Entry Value.
The User is entering the code in the textbox, before saving to the table, i want to check whethere code is already exist in the table or not.
Tried Code
cmd = New SqlCommand("Select code from table where code = '" & textbox1.Text & "' ", Con)
dr = cmd.ExecuteReader()
While dr.Read()
End While
If value is exist, then message to the 开发者_开发问答user "Already Exist" other wise save to the table.
Need Vb.net Code Help
Use SELECT COUNT instead and then check for that being greater than zero:
cmd = New SqlCommand("SELECT COUNT(*) from table where code = '" & textbox1.Text & "' ", con)
Dim NumRecords as Int32 = cmd.ExecuteScalar
IF NumRecords > 0 THEN...
Make code as primary key since you want it to be unique
if the value entered by the user in code is already existing in the table , VIOLATION of primary key sql exception will be thrown
Catch that exception and display a warning message!
精彩评论