Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to create counter in Asp.Net.

How should I create a counter?

It should be like a counter in a game where you have 4-5 minutes and need to complete a task and the counter moves in a descending order that it starts from 4 minues and ends with 00.
Posted
Comments
Richard C Bishop 24-Mar-14 13:38pm    
Just use some javascript and make a timer.

Create Count Down Timer using ASP.NET Timer Control and Ajax[^]

XML
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
        </asp:Timer>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </ContentTemplate>
</asp:UpdatePanel>


protected void Page_Load(object sender, EventArgs e)
{
    if (Session["CountdownTimer"] == null)
    {
        Session["CountdownTimer"] = new CountDownTimer(TimeSpan.Parse("2:30:00"));
        (Session["CountdownTimer"] as CountDownTimer).Start();
    }
}
protected void Timer1_Tick(object sender, EventArgs e)
{
    if (Session["CountdownTimer"] != null)
    {
        Label1.Text = (Session["CountdownTimer"] as CountDownTimer).TimeLeft.ToString();
    }
}

public class CountDownTimer
{
    public TimeSpan TimeLeft;
    System.Threading.Thread thread;
    public CountDownTimer(TimeSpan original)
    {
        this.TimeLeft = original;
    }
    public void Start()
    {
        // Start a background thread to count down time
        thread = new System.Threading.Thread(() =>
        {
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                TimeLeft = TimeLeft.Subtract(TimeSpan.Parse("00:00:01"));
            }
        });
        thread.Start();
    }
}


Code is ripped from here[^].

-KR
 
Share this answer
 
Comments
darshantani 24-Mar-14 19:42pm    
Hello Krunal Rohit,

That was very helping thanks.

Here If I want to add pause and start button how can I do that?

and If I want to create this timer once a press the button start or play what I need to do?

thanks in advance.
Krunal Rohit 25-Mar-14 0:29am    
See this,
http://msdn.microsoft.com/en-us/library/dd492144.aspx

http://msdn.microsoft.com/en-us/library/bb386404.aspx


-KR
Hi darshantani, you can follow this tutorial[^].

Another nice article can be found here[^]

Hope it helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900