Articles → ADO.NET → Catch primary key violation exception in

Catch primary key violation exception in

Software requirement

Prerequisite knowledge

Steps of execution

Create a new project

Picture showing project structure in visual studio

Click to Enlarge

Create a new table

Picture showing the table schema

Click to Enlarge

Add controls to the page

Picture showing 2 textboxes and a button on the screen

Click to Enlarge

Add code to handle primary key violation exception

try {
	string connectionstring = @"your_connection_string";
	using(SqlConnection connection = new SqlConnection(connectionstring)) {
		string query = string.Format("insert into Employee values('{0}','{1}')", txtEmailId.Text, txtFullName.Text);
		using(SqlCommand command = new SqlCommand(query, connection)) {
catch(SqlException ex) {
	if (ex.Number == 2627) {
		Response.Write("This is the primary key violation");
	else {
		Response.Write("This is the general error");

Code explanation


Picture showing the data inserted into the table

Click to Enlarge

Picture showing the error message when duplicate record is inserted into the table

Click to Enlarge

Posted By  -  Karan Gupta
Posted On  -  Tuesday, March 05, 2013


Your Email Id  
Query/FeedbackCharacters remaining 250