Articles → ADO.NET → Catch Primary Key Violation Exception In Ado.Net
Catch Primary Key Violation Exception In Ado.Net
Software Requirement
- Visual studio (any version) is installed on your machine.
- SQL server (any version) is installed on your machine.
Prerequisite Knowledge
- Basics about ado.net.
- Basics about SQL server.
- How to create a project using visual studio?
- Basics about asp.net controls.
- Exception handling in .net.
Steps Of Execution
- Create a new project
- Create a new table
- Add controls to the page
- Add code to handle primary key violation exception.
Create A New Project
Click to Enlarge
Create A New Table
Click to Enlarge
Add Controls To The Page
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
Click to Enlarge
Click to Enlarge