Ahmed Emad Ahmed Emad - 2 months ago 9
C# Question

linking timers to variables

I am making a food ordering desktop application , so i want to calculate time between ordering food and delivering food so i added timers to the app and made a start and end buttons , on starting i start a time and put it interval value ,make a variable counter, count and save its value on end button to database , what i want to made is to start a new timer dynamically on new orders and when ending an order stop its timer

i tried inserting 3 timers and made variables c1,c2,c3 and made a loop to start timers on every order if interval!=null , but i didn't know how to stop a specific timer on ending the order

code :

int c1=0;
int c2=0;
int c3=0;
private void button_start_Click(object sender, EventArgs e)
{
if (timer1.Interval == null)
{
timer1.Start();
timer1.Interval = 1000;
}
else if (timer2.Interval == null)
{
timer2.Start();
timer2.Interval = 1000;
}
else if (timer3.Interval == null)
{
timer3.Start();
timer3.Interval = 1000;
}


}

Answer

Well as you have not shown us any code, let me assume that you at least have a class to encapsulate order.

public class Order
{
    public int OrderNumber{get;set;}

    ///other properties
}

Now if you add following two properties and a method, your problem is resolved.

    public class Order
{
    public int OrderNumber{get;set;}

    //other properties

    public DateTime OrderPlacedOn{get;set;}
    public DateTime OrderCompletedOn{get;set;}

    public TimeSpan TimeToComplete()
    {
        if(OrderCompletedOn==DateTime.MinValue)//order not completed yet
            return TimeSpan.FromSeconds(0);

        return OrderCompletedOn - OrderPlacedOn;
    }
}

This saves you from keeping countless timers. You can set values of start and complete on clicking of your buttons.