Thursday, May 10, 2012

how to prevent Function Repetition in page refresh using c# asp.net


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) // If page loads for first time
    {
        // Assign the Session["update"] with unique value
        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
        //=============== Page load code =========================




        //============== End of Page load code ===================
    }
}

protected void btnDisplay_Click(object sender, EventArgs e)
{ 
    // If page not Refreshed
    if (Session["update"].ToString() == ViewState["update"].ToString())
    {
        //=============== On click event code ========================= 

        lblDisplayAddedName.Text = txtName.Text;

        //=============== End of On click event code ==================

        // After the event/ method, again update the session 

        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
    }
    else // If Page Refreshed
    {
        // Do nothing 
    }
}

protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);
  ViewState["update"] = Session["update"];
}