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
- Basics about ado.net.
- Basics about SQL server.
- How to create a project using visual studio?
- What are page events like load, prerender etc.
- Basics about asp.net controls and their events.
- Basics about state objects like session, viewstate etc.
Steps Of Execution
- Create a new project
- Create a new table
- Add button on the page
- Add code to avoid duplicate entries in database on refreshing the screen
Create A New Project
Click to Enlarge
Create A New Table
Click to Enlarge
Add Button On The Page
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
- Page load
- Button click event
- Page pre render
Output
Click to Enlarge