Friday, March 19, 2010

Insertion Same Data to database again

Insertion Same Data to database again, to stop events on the page getting fired on browser refresh we need to write bit of code to avoid it

In this example i've put a Label and a Button on the page, on click the label Text becomes "Stop again same data" and when i refresh the page label's text again becomes "Stop again same data"

Now in the Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it
Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed


public partial class _Default : System.Web.UI.Page
{
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 = "Stop again same date";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}
}

use This Page Render Class to Check Session


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