Daniel Lip
Daniel Lip

Reputation: 11317

How can I change timespan Hours Minutes Seconds according to each trackBar value without reseting the other values?

private void trackBarHours_Scroll(object sender, EventArgs e)
        {
            timespan = TimeSpan.FromHours(trackBarHours.Value);
        }

        private void trackBarMinutes_Scroll(object sender, EventArgs e)
        {
            timespan = TimeSpan.FromMinutes(trackBarMinutes.Value);
        }

        private void trackBarSeconds_Scroll(object sender, EventArgs e)
        {
            timespan = TimeSpan.FromSeconds(trackBarSeconds.Value);
        }

When I change for example the trackBarSeconds it's also changing the other hours and minutes timespans to 00. Even if the trackBarMinutes or trackBarHours in other values.

The other trackBars values not change but the timespan is reseting also the hours and minutes to 00. And I want to keep the values of the others when changing one of the trackBars.

Upvotes: 0

Views: 748

Answers (1)

Rufus L
Rufus L

Reputation: 37020

Assuming you have your timespan variable set correctly at the start, all you need to do is add or subtract the value specified by the appropriate scroll bar.

For example, lets assume all the scroll bars start at 0, so we'd start our timespan at zero:

private TimeSpan timeSpan = TimeSpan.Zero;

Next, we can create a method that sets the timespan to the correct value based on the hours, minutes, and seconds trackbar values by calling the constructor overload that takes in Hours, Minutes, and Seconds:

private void UpdateTimespan()
{
    timeSpan = new TimeSpan(trackBarHours.Value, trackBarMinutes.Value, 
        trackBarSeconds.Value);
}

Now we can simply call this method from each of the Scroll event handlers (or you may consider creating a single event handler and hooking all three controls' Scroll event to it):

private void trackBarHours_Scroll(object sender, EventArgs e)
{
    UpdateTimespan();
}

private void trackBarMinutes_Scroll(object sender, EventArgs e)
{
    UpdateTimespan();
}

private void trackBarSeconds_Scroll(object sender, EventArgs e)
{
    UpdateTimespan();
}

Upvotes: 1

Related Questions