简体   繁体   中英

how to insert countdown timer in asp.net c#

hii I want to insert a countdown timer in my project. right now i am using the following code:

{

    DateTime dt = (DateTime)Session["end_t"];
    DateTime dt_curr = DateTime.Now;
    TimeSpan ts = dt - dt_curr;
    lblTimer.Text = ts.Hours.ToString() + ":" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString();
    if (ts.Minutes == 0)
    {
        Timer1.Enabled = false;
        Response.Redirect("~/Online Exam/result2.aspx");
    }

the code works fine but when we move to some other page and then return back to main page the timer gets restarted. How can i overcome with this? Please help

It looks like you're resetting the end time on each page load, probably by doing something like:

protected void Page_Load(object sender, EventArgs e)
{
    DateTime start_time = DateTime.Now;
    DateTime end_time = start_time.AddMinutes(15);
    Session["end_t"] = end_time;
}

Instead, you should store the end time only if the timer is not already running:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["end_t"] == null) {
        DateTime start_time = DateTime.Now;
        DateTime end_time = start_time.AddMinutes(15);
        Session["end_t"] = end_time;
    }
}

Make a Master page and make your operations with timer there.
or
You can send the counter of timer to next page then do same operations with timer there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM