Friday 2 September 2016

ASP.NET - How to Detect Page Refresh Each Time

Posted by : Manav Pandya


ASP.NET - How to Detect Page Refresh Each Time


ASP.NET - How to Detect Page Refresh Each Time ?


Hello readers

Today i came with another article which shows How to Detect Page Refresh in ASP.NET  Each time .

This is important to resolve a problem that occur when we try to insert a data into Database , in which we found that each time page is refreshed , blank record will be inserted .

So here i have solution for that , so try it .

For that you have to place textbox and label to detect page refresh .

Following is a code that shows the same 




<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Manav Pandya  Page Refresh Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<br />
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Button" /></div>
</form>
</body>
</html>


Next step i have taken a session variable , and assigned date and time to it .

Aim is to check when button is clicked Viewstate variable and Session variable value are same or not .




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 = "Hello Manav Pandya";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "This Page is Refeshed - Manav";
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}


I hope you may like it .

If you have any query regarding this than comment it .

If you want code for that tell me the same .

Thanks my readers .