user6741701 user6741701 - 1 month ago 7x
ASP.NET (C#) Question

Convert Timespan - Gridview

The below code works. The last line formats the code as dd:hh:mm. How can I get it just to show as hh:mm. If I change the last line to

e.Row.Cells[4].Text = timeSpent.ToString(@"hh\:mm");

I get an exception as it goes over 24hrs. The aim is to get the output as 26:30 instead of 01:02:30

My code is:

TimeSpan timeSpent = TimeSpan.Zero;

protected void GridViewFortNight_RowDataBound(object sender, GridViewRowEventArgs e)
var tempTimeCalc = "";

if (e.Row.RowType == DataControlRowType.DataRow)
tempTimeCalc = e.Row.Cells[4].Text.ToString();

timeSpent += TimeSpan.Parse(tempTimeCalc);

else if (e.Row.RowType == DataControlRowType.Footer)

e.Row.Cells[4].Text = timeSpent.ToString(@"dd\:hh\:mm");




It's not supported by the built-in format strings. You'll have to go a bit deeper and do some of the formatting yourself. It's not that bad, though:

e.Row.Cells[4].Text = string.Format("{0:00}:{1:00}", (int)timeSpent.TotalHours, timeSpent.Minutes);