3

I have datagridview whose datasource is datatable.

I have two columns in datagridview:

NAME, IN TIME

After the datagridview is loaded, I want to add a new column called DURATION which is a timer column i.e. based on the IN TIME, DURATION column should display a stopwatch with the timespan interval of CURRENT TIME-IN TIME.

How do I make the DURATION column stopwatch to continue the timer for every seconds like digital clock?

CST RAIZE
  • 428
  • 1
  • 5
  • 18

1 Answers1

2

You can add a string column to DataTable and use it as duration column. Then you can subscribe to Tick event of a timer which you set it's interval to 1000 and show the result of count down timer in duration column:

void timer_Tick(object sender, EventArgs e)
{
    foreach( DataRow row in YourDataTable.Rows)
    {
        var diff = row.Field<DateTime>("DateTimeColumn").Subtract(DateTime.Now);
        if(diff.TotalSeconds>0)
        {
            row["DurationColumn"] = string.Format("{0} d {1:D2}:{2:D2}:{3:D2}", 
                                       diff.Days, diff.Hours, diff.Minutes, diff.Seconds);
        }
        else
        {
            row["DurationColumn"] = "0 d 00:00:00";
        }
    }
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • I want to display the duration changes in datagridview. – CST RAIZE Feb 27 '16 at 14:26
  • 2
    Above code performs what you need. It shows a count down timer in the cells of duration column that shows duration between specified time and now. The timer, updates cells each second. – Reza Aghaei Feb 27 '16 at 14:32
  • I just have a doubt. After assigning a datagridview.datasource=datatable; If I make any changes in datatable, will it be reflected in datagridview immediately – CST RAIZE Feb 27 '16 at 14:35
  • 2
    When you change a value in `DataTable`, changes will be reflected to `DataGridView` immediately. `DataTable` supports two way data binding. – Reza Aghaei Feb 27 '16 at 14:39
  • Since the IN TIME is always lesser than CURRENT TIME. var inTime = row.Field("IN TIME"); var currentTime = DateTime.Now; var diff = currentTime - inTime; – CST RAIZE Feb 27 '16 at 17:07
  • I made this small change. It works perfectly. Thanks @Reze Aghaei – CST RAIZE Feb 27 '16 at 17:09