frenchie
frenchie

Reputation: 51927

TimeSpan DataFormatString in Gridview

I have a gridview with an ObjectDataSource that comes from a linq query.

One of the variables of the source is a timespan and I'm binding a boundfield with the DataField="MyTimeSpanVariable". The data contains times in seconds and minutes and very rarely in hours.

The data displays fine in its native format but when I add HtmlEncode="false" DataFormatString="{0:hh:mm:ss}" to the boundfield properties in the aspx page, it crashes on the MyGridView.Databind() line. What am I doing wrong?

Thanks.

Upvotes: 6

Views: 14719

Answers (5)

Obi Dabibobo
Obi Dabibobo

Reputation: 61

See http://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx Eq to use in Asp.Net MVC Metadata:

DisplayFormat(DataFormatString = "{0:hh\\:mm\\:ss}")

Upvotes: 6

Paul George
Paul George

Reputation: 1817

From the aspx/ascx this would be something like

HtmlEncode="false" DataFormatString="{0:mm\:ss}" 

Upvotes: 3

Hasan
Hasan

Reputation: 154

If you like, you can try formatting your field on the Grid's RowDataBound event.

For example:

Protected Sub YourGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles YourGridView.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        If e.Row.DataItem("YourColName") Then
            'Do formatting
        End If
    End If
End Sub

Upvotes: -1

Holf
Holf

Reputation: 6432

I believe you need to escape the second ':' if you are using C#. For example:

DataFormatString=@"Time is {0:H\:mm}";

Upvotes: 4

Brunis
Brunis

Reputation: 1063

I have the same problem!:
FormatException on DataFormatString="Mødetidspunkt er {0:H:mm}"

You can't use two colons, so use the short time format specifier.

DataFormatString="Time is {0:t}"
t is the equivalent of HH:mm
T is the equivalent of HH:mm:ss

See "Standard DateTime Format Strings".

Upvotes: 4

Related Questions