Tuesday, January 17, 2012

Detecting browser refresh or F5 click on page in c#

Friends,
     I found an interesting problem in my application.
after saving data in database I clear the page and reset all control at the page. but If I click on browser refresh or press F5 on keyboard, Page get post back and save/ update or button click execute again with old values which were exists just before reset data.
So now the records or operation process again which is wrong in my condition and I do not want to process that code again.
I search a lot over Internet for the solution of the above problem and after a lot of findings I found a working solution for me.

So I am going to explain the solution for the convenience of the other developers

#region code to determine Refresh state of Page ie. button click or F5 hit
    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());
        _isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString());
    }

    protected override object SaveViewState()
    {
        Session["__ISREFRESH"] = _refreshState;
        object[] AllStates = new object[2];
        AllStates[0] = base.SaveViewState();
        AllStates[1] = !(_refreshState);
        return AllStates;
    }
    #endregion

   protected void imgbtnSave_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            if (!_isRefresh)
            {
         // your code goes here
        }
    }
    }
if  _isRefresh variable is true then user refresh the browser or click F5 


hope this code helps you.....................

No comments:

Post a Comment