Create Count Down Timer Using ASP.NET Timer Control

In this post I’m gonna tell, how one can Create Count Down Timer Using ASP.NET Timer Control. Its a simple and easy process.

Will first place the code and later on will explain it.

Default.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID= "SM1" runat="server"></asp:ScriptManager>
<asp:Timer ID="timer1" runat="server" 
Interval="1000" OnTick="timer1_tick"></asp:Timer>
</div>
<div>
<asp:UpdatePanel id="updPnl" 
runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTimer" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
</Triggers>
</asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

 


 

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class timercontrol : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!SM1.IsInAsyncPostBack)
            Session["timeout"] = DateTime.Now.AddMinutes(120).ToString();
    }
    protected void timer1_tick(object sender, EventArgs e)
    {
        if (0 > DateTime.Compare(DateTime.Now,
        DateTime.Parse(Session["timeout"].ToString())))
        {
            lblTimer.Text = "Number of Minutes Left: " +
            ((Int32)DateTime.Parse(Session["timeout"].
            ToString()).Subtract(DateTime.Now).TotalMinutes).ToString();
        }
    }
}

Code Explanation

In default.aspx page, I’ve used Timer Control and update panel, and lable control inside the update pannel.

In the Default.aspx.cs page in the page load event, I’ve  created a session variable and ensure that the value of the session variable doesn’t get updated due to the async post back caused by the AsyncPostBackTrigger.

If we do not include the IsAsyncPostBack check, our Session variable will always get updated with the latest or current date time value.

You can see in the image below, how it looks.

timer control
 

 

 

 

 

Download Demo Example


JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar