I managed to figure out a way to check for a primary key violation. My code modifications follow:
Public Function InsertNewUser(ByVal _ConnString As String, ByVal UserAccess As UserAccess.Access) As Integer
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = _ConnString
cmd.Connection = conn
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.CommandText = "dbo.Access_Insert"
With cmd.Parameters
.AddWithValue("@Username", UserAccess.Username)
.AddWithValue("@RealName", UserAccess.Realname)
.AddWithValue("@accesslevel", 1)
.AddWithValue("@Email", UserAccess.Email)
.AddWithValue("@Webpage", UserAccess.Webpage)
.AddWithValue("@Sig", UserAccess.Sig)
.AddWithValue("Occupation", UserAccess.Occupation)
.AddWithValue("@Personal", UserAccess.Personal)
.AddWithValue("JoinDate", DateTime.Now)
.AddWithValue("@Password", UserAccess.Password)
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As SqlException
Return ex.ErrorCode
Finally
conn.Close()
End Try
Return 0 ' success
End Function
As you can see on a error I now return the SqlException ErrorCode, within the calling function I can now check for a primary key violation using the following code:
Select Case (Result)
Case 0
' Insert was successful
Exit Sub
Case -2146232060
' We have a primary key violation, do something to handle it
Exit Sub
End Select
Using this method I find no matter what the error, as long as I know the error number and the meaning of the error I can handle the code in my applications
I hope this helps someone in the same situation as me out
Enter your message below
Sign in or Join us (it's free).