Articles → ADO.NET → Catch Primary Key Violation Exception In Ado.Net

Catch Primary Key Violation Exception In Ado.Net






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