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

Catch primary key violation exception in ado.net





  1. Software requirement
  2. Prerequisite knowledge
  3. Steps of execution
  4. Create a new project
  5. Create a new table
  6. Add controls to the page
  7. Add code to handle primary key violation exception.
  8. Code explanation
  9. Output.

Software requirement




  1. Visual studio (any version) is installed on your machine.
  2. SQL server (any version) is installed on your machine.

Prerequisite knowledge




  1. Basics about ado.net.
  2. Basics about SQL server.
  3. How to create a project using visual studio?
  4. Basics about asp.net controls.
  5. Exception handling in .net.

Steps of execution




  1. Create a new project
  2. Create a new table
  3. Add controls to the page
  4. Add code to handle primary key violation exception.



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 5, 2013

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250