Monday, July 18, 2011

Time Increment in c# Using Timer Control


HTML CODE


<asp:ScriptManager ID="ScriptManager1" runat="server">
                </asp:ScriptManager>                
                 <asp:UpdatePanel ID="UpdatePanel1" runat="server">

                    <ContentTemplate>
                        <asp:Timer ID="Timer2" runat="server" Interval="1000" ontick="Timer2_Tick">
                        </asp:Timer>
                        <asp:Label ID="lblhrs" runat="server"></asp:Label>
                        <asp:Label ID="lblmin" runat="server"></asp:Label>
                        <asp:Label ID="lblsec" runat="server"></asp:Label>
                    </ContentTemplate>
                </asp:UpdatePanel>

C#  CODE


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;

public partial class Default2 : System.Web.UI.Page
{
    static int m = 1;
    static int s = 1;
    static int h = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblmin.Text = "00";
            lblsec.Text = "00";
            lblhrs.Text = "00";
        }
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        UpdatePanel1.Visible = true;

        //hours

        if (m >= 60)
        {
            lblhrs.Text = h.ToString();
            h++;
        }
        //minuts
        if (s == 60)
        {
            if (m >= 10)
            {
                lblmin.Text = ":" + m.ToString();
            }
            else
            {
                lblmin.Text = ":" + "0" + m.ToString();
            }
            s = 0;
            if (s >= 10)
            {
                lblsec.Text = ":" + s.ToString();
            }
            else
            {
                lblsec.Text = ":" + "0" + s.ToString();
            }
            m++;
        }

        //seconds
        if (s >= 10)
        {
            lblsec.Text = ":" + s.ToString();
        }
        else
        {
            lblsec.Text = ":" + "0" + s.ToString();
        }
        s++;

    }
}

No comments:

Post a Comment