jeudi 3 décembre 2020

How to make count up timer in C# Web Forms

I managed to make the below code for countdown and when you choose a number from the dropdownlist it will start counting from that number to 0, now I want to reverse it and make the timer count up and when you choose a number from the dropdownlist it adds up to the timer, also I made two buttons first one play/continue the timer and the other one to stop it,

what do I need to change in my codes to make it count up instead of count down? and is there any way to make the stop button reset the timer on the 2nd click?

here is my code,

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Timers;
using System.Threading;


namespace WebApplication25464
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        int tt;

        protected void Page_Load(object sender, EventArgs e)
        {
            String t10 = "10";
            String t20 = "20";
            String t30 = "30";
            String t40 = "40";

            if (!IsPostBack)
            {
                DropDownList1.Items.Add(t10);
                DropDownList1.Items.Add(t20);
                DropDownList1.Items.Add(t30);
                DropDownList1.Items.Add(t40);



                Session["Timer"] = DateTime.Now.AddMinutes(1).ToString();
               
            }

            if (DropDownList1.SelectedValue == t10)
            {
                tt = 10;

            }
            else if (DropDownList1.SelectedValue == t20)
            {
                tt = 20;
            }
            else if (DropDownList1.SelectedValue == t30)
            {
                tt = 30;
            }
            else if (DropDownList1.SelectedValue == t40)
            {
                tt = 40;
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        protected void Timer1_Tick(object sender, EventArgs e)
        {

            if (DateTime.Compare(DateTime.Now, DateTime.Parse(Session["Timer"].ToString())) < 0)
            {
                TimeInfo.Text = "Time Left : " + ((Int32)DateTime.Parse(Session["Timer"].ToString()).Subtract(DateTime.Now).TotalMinutes)
                    .ToString() + "Minute" + (((Int32)DateTime.Parse(Session["Timer"].ToString()).Subtract(DateTime.Now).TotalSeconds) % tt)
                    .ToString() + "Seconds";
            }
            else
            {
                TimeInfo.Text = "Time Expired";
            }
        }

        protected void Button1_Click1(object sender, EventArgs e)
        {
            Timer1.Enabled = true;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Timer1.Enabled = false;
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire