none
is there a code or information in exception to judge its an "violation of primary key " error?

    Question

  • hi

       i have a try catch and in try is the code of operation of database.

      i  would like to ask is there a code or information in exception to judge its an "violation of primary key " error?

      i know in exception.message it begins with "violation of primary key " ,but i would like to ask,if there is a code or sth like that so that i can write code to judge its an "violation of primary key " error?

       thank u very much

    best regards

    martin

    Wednesday, July 24, 2013 4:54 PM

Answers

  • You can catch SqlException and check for error code. If error code is 2627 then error is related to unique key or primary key constraint.

    try
    {
    
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        if (ex.ErrorCode == 2627)
        {
            MessageBox.Show("Unique key or Primary key duplication")
        }
    }


    Gaurav Khanna | Microsoft VB.NET MVP | Microsoft Community Contributor

    Wednesday, July 24, 2013 7:09 PM

All replies

  • You can catch SqlException and check for error code. If error code is 2627 then error is related to unique key or primary key constraint.

    try
    {
    
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        if (ex.ErrorCode == 2627)
        {
            MessageBox.Show("Unique key or Primary key duplication")
        }
    }


    Gaurav Khanna | Microsoft VB.NET MVP | Microsoft Community Contributor

    Wednesday, July 24, 2013 7:09 PM
  • hi Khanna Gaurav

        yes it works.thank u very much for ur kindness help.

       have a nice day

    best regards

    martin

    Thursday, July 25, 2013 7:56 AM