{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}Next, we create the Tick handler, which will retrieve the current time from the HiddenField, add one second to it, and display it in the Literal field, then it will save the new value to the HiddenField to be used again in a second:
protected void Timer1_Tick(object sender, EventArgs e) {
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
}lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString(); |
If we run this now the timer will begin counting up as soon as the page is loaded. It is already fully-functional. But to test it, let’s add a textbox and a button so that we can postback the page and demonstrate how to keep the timer counting up regardless.
protected void btn_Submit_Click(object sender, EventArgs e) {
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
} |
Our ASPX page looks like this:
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
protected void Timer1_Tick(object sender, EventArgs e)
{
protected void btn_Submit_Click(object sender, EventArgs e)
{
}
{
if (! IsPostBack)
{
}{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
}lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
}