Doruk Ayar
Doruk Ayar

Reputation: 344

How To Make a StopWatch With C#

I just want to ask that if I can make a stopwatch with C# I tried:

        private void button2_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        int st = 00;
        int m = 00;

        string stime = "00:00";
        if(st == 60)
        {
            m++;
            st = 00;
        }
        else
        {
            st++;
        }
        if (m == 60)
        {
            m = 00;
        }
        if(st < 10)
        {
            st = 0 + st;
        }
        if(m < 10)
        {
            m = 0 + m;
        }
        stime = m.ToString() + ":" + st.ToString();
        label3.Text = stime;
    }

this but it didn't worked. My timer is setted up and the interval of the timer is 1000ms. Can someone help me?

Upvotes: 0

Views: 12993

Answers (1)

user1562155
user1562155

Reputation:

It looks to me, that you are more likly to make a watch rather than a stopwatch?

If you're making a stopwatch, I think you need a field/property in your class that holds the starting time:

private DateTime _start;
private void button2_Click(object sender, EventArgs e)
{
    _start = DateTime.Now;
    timer1.Start();
}

and then in timer1_Tick you can do:

private void timer1_Tick(object sender, EventArgs e)
{
    TimeSpan duration = DateTime.Now - _start;
    label3.Text = duration.ToString(<some format string>);
}

It seems that your current code in timer1_Tick only has local variables and therefore always will produce the same time? :-)

Upvotes: 6

Related Questions