Articles → .NET → Avoid Duplicate Entries In Database On Refreshing The Screen In Asp.Net

Avoid Duplicate Entries In Database On Refreshing The Screen In Asp.Net






Software Requirement





Prerequisite Knowledge




  1. Basics about ado.net.
  2. Basics about SQL server.
  3. How to create a project using visual studio?
  4. What are page events like load, prerender etc.
  5. Basics about asp.net controls and their events.
  6. Basics about state objects like session, viewstate etc.

Steps Of Execution




  1. Create a new project
  2. Create a new table
  3. Add button on the page
  4. Add code to avoid duplicate entries in database on refreshing the screen



Create A New Project




Picture showing the project structure of the web application in solution explorer
Click to Enlarge


Create A New Table




Picture showing the table schema of the Employee table
Click to Enlarge


Add Button On The Page




Picture showing a web page with a button to insert a value in the Employee table
Click to Enlarge


Add Code To Avoid Duplicate Entries In Database On Refreshing The Screen




protected void Page_Load(object sender, EventArgs e) {
	if (!IsPostBack) {
		Session["update"] = "N";
	}
}
protected void Button1_Click(object sender, EventArgs e) {
	if (Convert.ToString(ViewState["update"]) == Convert.ToString(Session["update"])) {
		string connectionstring = @"connection_string";
		using(SqlConnection connection = new SqlConnection(connectionstring)) {
			connection.Open();
			string query = string.Format("insert into Employee values('{0}','{1}')", "abc@abc.com", "test name");
			using(SqlCommand command = new SqlCommand(query, connection)) {
				command.ExecuteNonQuery();
				Session["update"] = "Y";
			}
		}
	}
}

protected void Page_PreRender(object sender, EventArgs e) {
	ViewState["update"] = Session["update"];
}



Code Explanation




  1. Page load
  2. Button click event
  3. Page pre render









Output


Picture showing the table rows in the Employee table
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, March 13, 2013

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250