문제

I have two buttons in my Application "Start" and "Stop".

When a user clicks on the Start button, LabelStartTime.Text contains current System time(HH:MM AM/PM).

When a user clicks on the Stop Button LabelStopTime.Text contains current System time and LabelTotle.Text

I am trying to show the Time difference in Minutes. I only know how to get current time to the Label value.

lblCurrentTime.Text = DateTime.Now.ToShortTimeString(); // Get current time

        private void button1_Click(object sender, EventArgs e)
    {
        lblCurrentTime.Text = DateTime.Now.ToShortTimeString(); // get system time to the  Start time 

        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
    }


    private void button2_Click(object sender, EventArgs e)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Stop();

        textBox1.Text = DateTime.Now.ToShortTimeString();
        lblCurrentPrice.Text = Stopwatch.Elapsed.TotalMinutes; 



    }

this -- > Stopwatch.Elapsed.TotalMinutes Given Error

도움이 되었습니까?

해결책

Consider using the System.Diagnostics.Stopwatch class. Call Start() when the first button is clicked, and Stop() when the second button is clicked. Then, the difference in minutes is Stopwatch.Elapsed.TotalMinutes;

In the code example you've now given you've declared two new stopwatches that only exist within the scope of each method.

Declare it outside the methods like this:

Stopwatch stopWatch = new Stopwatch();

private void button1_Click(object sender, EventArgs e)
{
    // get system time to the  Start time 
    lblCurrentTime.Text = DateTime.Now.ToShortTimeString(); 

    stopWatch.Start();
}

private void button2_Click(object sender, EventArgs e)
{
    stopWatch.Stop();

    textBox1.Text = DateTime.Now.ToShortTimeString();
    lblCurrentPrice.Text = Stopwatch.Elapsed.TotalMinutes; 
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top