• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 573
  • Last Modified:

Calculate Time worked in Gridview

I am working on a program to calculate hours worked for an employee. How do I take two time values from two gridview columns and add them together? Should I use a template field?
1 Solution

Is the data in both columns expressed as hours or Date/Time values like a Start and End time?

fishbowlstudiosAuthor Commented:
DateTime Values come from a Database via a LINQ query. I assume they are coming from a DateTime datatype.
Miguel OzSoftware EngineerCommented:
Yes you can use a template field, but I think you are better off adding this value to your LINQ collection, so that it comes directly on the binding.

If you proceed with template field (for whatever reason), then you need code similar to: (assumption your employee object contains start and enddate properties)
    protected void CustomerGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        //This event is executed multiple times per row due to data bound issues.
        if (e.Row.RowType == DataControlRowType.DataRow)
            Employee item = e.Row.DataItem as Employee;
            DateTime newDT = item.endDate.Subtract(item.startDate);                      
            //Assign newDT to your template field.
Gustav BrockCIOCommented:
TimeSpan it is:

            Employee item = e.Row.DataItem as Employee;
            TimeSpan hoursWork = item.endDate.Subtract(item.startDate);
            //Assign hoursWork to your template field.

Or, if you rather have two timespans:

            Employee item = e.Row.DataItem as Employee;
            TimeSpan workHours = item.workPeriod1.Add(item.workPeriod2);
            //Assign workHours to your template field.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now