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

Catch primary key violation exception in ado.net
























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)) {
		connection.Open();
		string query = string.Format("insert into Employee values('{0}','{1}')", txtEmailId.Text, txtFullName.Text);
		using(SqlCommand command = new SqlCommand(query, connection)) {
			command.ExecuteNonQuery();
		}
	}
}
catch(SqlException ex) {
	if (ex.Number == 2627) {
		Response.Write("This is the primary key violation");
		return;
	}
	else {
		Response.Write("This is the general error");
		return;
	}
}



Code explanation





Output




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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250