Friday, 14 October 2016

Primary key validation in C#

restrict duplicate primary key


Description:

in this example we explain that how to validate primary key in C# like suppose if user enter duplicate primary key then sqlException is raised or throw from ADO.Net so end user cannot understand the sql message proper so display proper sqlexception message to user then use the below code.

Here we use Try Catch block to capture this exception and display proper message to user.

Code:

try
{
    // Your coding logic
}
catch (SqlException ex)
{
    if (ex.Number.Equals(2627))
    {
          // Display here Primary Key duplicate error
          lblError.Text = "Duplicate Number! Try Different";
    }
}


This entry was posted in :

0 comments:

Post a Comment