Tuesday, September 18, 2012

How to avoid the button events on Refresh of page


I have .aspx page that page inserts the data to the database on a button click. But when i press the button it is going right. i m getting the Successfully message as " successfully inserted data". In this situation if i press "F5" or Refresh the page it is firing the button click event. Why it should be ? How to avoid this condition ?

Solution to the above problem is -

Add this in your class:

#region Browser Refresh
private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
refreshState = bool.Parse(AllStates[1].ToString());
if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}

protected override object SaveViewState()
{
Session["ISREFRESH"] = refreshState;
object[] AllStates = new object[3];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(refreshState);
return AllStates;
}

#endregion

And in your button click do this:
protected void Button1_Click(object sender, EventArgs e)
{
if (isRefresh == false)
{
Insert Code here

This will do the trick ...

No comments: