May 7, 2013

How To Validate Primary Key

If user enter duplicate Primary Key, then SqlException is raise from ADO.Net. To alert end user about duplication, use Try Catch block to capture this exception and show appropriate error to end user. To do so, use this

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

Stay tune :)

No comments:

Post a Comment