Pages

Monday, May 30, 2011

Check to see if refresh button is clicked to avoid click event fired again


When we click submit button it runs the code and does its job now, when we press refresh button of the browser it again fires the click event and the code reruns causing the duplicate entry in the database or so.

So to avoid this here is the code-
protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack){Session["CheckRefresh"] =
 Server.UrlDecode(System.DateTime.Now.ToString());
}

}
protected void Button1_Click(object sender, EventArgs e)
{
 if (Session["CheckRefresh"].ToString() ==ViewState["CheckRefresh"].ToString())
 {
  Label1.Text = "Hello";
  Session["CheckRefresh"] =Server.UrlDecode(System.DateTime.Now.ToString());
 }
 else
 {
  Label1.Text = "Page Refreshed";
 }
}

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

No comments:

Post a Comment