You don't have to do anything in your code to prevent adding rows that contain duplicate key field(s), the database server to do that if you designed the table to require key fields to be unique values. All your program needs to do is catch the db server's exception. If the record already exists then an exception is thrown, line 32 will not get executed.
IMO you have too many checks inside the try/catch block. Inside the try/catch block all you need are the lines that actualy do the insertion, the database server will do the rest.
Ancient Dragon
Achieved Level 70
32,128 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 69
cmd2 = New SqlCommand("select count(*) from ProgramDetails.Subjects where IDNumber = '" & txtIDNumber.Text & "'", cn)
queryResult = cmd2.ExecuteScalar
If queryResult > 0 Then
So basically you are telling your program that if count is greater that 0 (records have been found) do the insert. If it's less or equal to 0 (impossible to be less or no matches found) error the user.
change If queryResult > 0 Then to If queryResult = 0 Then
adam_k
Veteran Poster
1,057 posts since Jun 2011
Reputation Points: 274
Solved Threads: 205
Skill Endorsements: 11
Are you able to change the table schema? If yes, then use one or more fields as the unique key. Auto id is nice, but not very usefor for preventing duplicate records.
Ancient Dragon
Achieved Level 70
32,128 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 69
Question Answered as of 2 Months Ago by
Ancient Dragon
and
adam_k