C# – btnAdd_Click fires when i press F5

asp.netc++

Hi I've a simple code to insert data into db in button click event. It is executing fine and insert data into db. After inserting data if i press f5 button it is again inserting a new row into db with the same values.

Button click event fires on each f5 button (refresh)

Wat is the problem?

Thank you,
Nagu

Best Solution

This is as designed. When you press F5 you are redoing what you just did which was a postback. To prevent this you have an endless amount of solutions such as:

Use a session variable on initial load and once it is posted the first time (saved), clear the value. Make sure you are checking for the presence of this value.

// On inital page load for data entry store a key.
// This is a basic example, you should have a session wrapper
Session["Unsaved"] = 1;

// When you do the save logic make sure you check this session variable and save if
// it still exists.
if (Session["Unsaved"] != null)
{
  // Save data here
  Session.Remove("Unsaved");
}
else
{
  // Show message that save has already completed or session has expired.
}

You could also do the check DB side and verify that you are not inserting identical data (which may not work as it could be valid in your scenario)

In the past I have prevented this with edits for example by storing a revision number and having it submit the revision number with the posted data. When saving, if the revision numbers don't match (since it is changed with each update and the check is done DB side) then the update fails and I would display a message.

For new data, you could also do a Response.Redirect to a 'complete' page which gives them updated information of success / failure. If they hit refresh, they will just be reloading the completed page and not the page that was doing the insert / updating.

Again there are so many different solutions. Nothing is perfect for every scenario so you will need to find out which works best for you.