How do I catch duplicate record exception?

  • Thread starter Thread starter Hexman
  • Start date Start date
H

Hexman

Hello All,

How do I catch duplicate record attempted to be added exception? As in:

Catch ex As Exception


Thanks,

Hexman
 
Catch ex As Exception
If InStr(1, ex.ToString, "duplicate key") > 0 Then

lblMessage.Text = " User already exists cannot insert
duplicate value."

Else

lblMessage.Text = ex.ToString()

End If

Finally
'close the connection here, the Finally part will always
execute
Conn.Close()
 
Thanks Scorpion,

I just thought there would be a error number that could be tested for this condition, like H_Result.

Hexman
 
Hexman said:
How do I catch duplicate record attempted to be added exception? As in:

Catch ex As Exception

Start with this, generate the Exception and see what you get.

? ex.GetType().ToString()

Assuming this isn't just System.Exception, then change the Catch to
catch the required Type and examine each property of that subclass,
something like

Catch ex As ODBCException

? ex.Errors.Count
? ex.InnerException.ToString()

and so on. If you're lucky, you'll find something that identifies a
duplicate record exception explicitly. If not, you'll have to fall back
on looking for some text in the Message. This will work but isn't
ideal; the message generated could change with, say, an upgrade to the
DBMS software, thereby breaking your program.

HTH,
Phill W.
 
Back
Top