CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
How to format DateTime in GridView BoundColumn and TemplateColumn?

By Satheesh babu
Posted On Sep 25,2008
Article Rating:
Average Rating: 3.67
No of Ratings: 3
No of Comments: 28
Category: ASP.Net
Print this article.

How to format DateTime in GridView BoundColumn and TemplateColumn?

 

Most often, we will get requirements to display date in GridView column. To format the date displayed in the GridView column, we can use “DataFormatString” to set the DateTime format in a Bound Column. This article will helps us formatting the date string in GridView column when we use Bound column and Template column. At the end of this article, we will have a list of date formatting string that can be used to format the date to different formats.

 

Format Date in Bound Column

Consider we have a GridView that displays Employee information with FirstName, LastName, Email and DOB, where the DOB is stored with time in database.

 

<asp:GridView ID="gvUsersBF" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4">

                    <Columns>

                        <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />

                        <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />

                        <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />

                        <asp:BoundField DataField="DOB" HeaderText="Date Of Birth" ReadOnly="True" />                                           

                    </Columns>

                    <FooterStyle BackColor="White" ForeColor="#330099" />

                    <RowStyle BackColor="White" ForeColor="#330099" />

                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />

                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />

                    <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />

        </asp:GridView>

 

To make the DOB column to display a short date format without the time, we need to include DataFormatString = "{0:d}"  for the BoundColumn to display a short date.

 

<asp:BoundField DataField="DOB" HeaderText="Date Of Birth" DataFormatString = "{0:d}"   ReadOnly="True" />           

 

Making the above setting only will not work. It is because, by default, HTML encode is turned “on” to prevent executing some dangerous script when injected through cross site scripting attacks. Because of this default setting, the text in the column will be encoded so that the cross site scripting is not executed. In order to make the above setting work, we need to make the HtmlEncode property of BoundColumn to false.

 

<asp:BoundField DataField="DOB" HeaderText="Date Of Birth" HtmlEncode="False" DataFormatString = "{0:d}"   ReadOnly="True" />           

                    

For Long Date,

<asp:BoundField DataField="DOB" HtmlEncode="False" DataFormatString = "{0:D}" HeaderText="Date Of Birth[Long Date]" ReadOnly="True" /> 

 

For Long Time,

<asp:BoundField DataField="DOB" HtmlEncode="False" DataFormatString = "{0:T}" HeaderText="Date Of Birth[Long Time]" ReadOnly="True" />


Hence, setting HtmlEncode="False" for the bound column will do the magic.

 

 




Format Date in Template Column

Sometimes we will also use Template column to display the date inside a child control like Label.

 

<asp:GridView ID="gvUsersBF" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4">

                    <Columns>

                        <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />

                        <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />

                        <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />

<asp:TemplateField HeaderText="Date Of Birth[Short Date]">

                        <ItemTemplate>

                        <asp:Label ID="lblDOB" runat="server" Text='<%# Bind("DOB") %>'></asp:Label>

                        </ItemTemplate>

                        </asp:TemplateField>                         

 </Columns>

                    <FooterStyle BackColor="White" ForeColor="#330099" />

                    <RowStyle BackColor="White" ForeColor="#330099" />

                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />

                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />

                    <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />

        </asp:GridView>

 

To bind the database column value to the child control we either use Bind() or Eval() methods. If you see the above code, we have used Bind() to bind DOB to the text property of Label control.

 

Text='<%# Bind("DOB") %>'

 

Using Eval in the place of Bind will also work. You use the Eval method when the control will only display values. You use the Bind method when users can modify a data value—that is, for data-update scenarios. 

 

These binding methods can take the formatting string as the next argument to set the format of the date displayed.

 

<ItemTemplate>

                        <asp:Label ID="lblDOB" runat="server" Text='<%# Eval("DOB","{0:d}") %>'></asp:Label>

                        </ItemTemplate>

                        </asp:TemplateField>   

 

For Long Date,

                        <asp:TemplateField HeaderText="Date Of Birth[Long Date]">

                        <ItemTemplate>

                        <asp:Label ID="lblDOB" runat="server" Text='<%# Bind("DOB","{0:D}") %>'></asp:Label>

                        </ItemTemplate>

                         </asp:TemplateField>

 

For Long Time,

                       <asp:TemplateField HeaderText="Date Of Birth[Long Time]">

                        <ItemTemplate>

                        <asp:Label ID="lblDOB" runat="server" Text='<%# Bind("DOB","{0:T}") %>'></asp:Label>

                        </ItemTemplate>

                        </asp:TemplateField> 

   

 

The following table shows some date format strings that can be used to format date in GridView columns,

Format Pattern

Name

Example

d

Short date

11/8/2008

D

Long date

Sunday, August 11, 2008

t

Short time

3:32 PM

T

Long time

3:32:00 PM

f

Full date/time
(short time)

Sunday, August 11, 2008 3:32 PM

F

Full date/time
(long time)

Sunday, August 11, 2008 3:32:00 PM

g

General date/time
(short time)

8/11/2008 3:32 PM

G

General date/time
(long time)

8/11/2008 3:32:00 PM

m or M

Month day

August 11

r or R

RFC 1123

Sun, 11 Aug 2008 8:32:00 GMT

s

Sortable date/time

2008-08-11T15:32:00

u

Universable sortable date/time

2008-08-11 15:32:00z

U

Universable sortable date/time

Sunday, August 11, 2008 11:32:00 PM

y or Y

Year month

August, 2008

 

 

Downloads

Source Code 

 

Conclusion

The databound controls like GridView are extensively used in web applications to display data. We will always have requirement to format the data that is displayed, most of the time formatting the date time strings. This article will help us to format the date into many useful formats and it can be used as a future reference for formatting date time strings.

Happy Coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
form
Savvy analysis , For my two cents , if someone needs a DD 137-5 , my friend encountered a sample document here "http://pdf.ac/4w2P6s"
Dste Formate Pattern
Its very helpfull..
thank you so much.
Dste Formate Pattern
Its very helpfull..
thank you so much.
thank you
thank you very very much
Encylopedia for date formating
Thanks....
helpful
Thank you for helping me
thanku...
Thanku.....worked a lot....really nice article.......
thnakz
thank u very much..................
Excellent
very nice
Complete solution for date formatting patterns
Thanx a lot...i was looking for the same and i got it.
cheers.
Nice Article
Very Nice article.
Thank You
Thank you guy, very good code
very good
Thank you guy, very good code
Another Format..
<asp:Label ID="LengthLabel" runat="server" Text='<%# Eval("[Length]","{0:hh:mm}") %>' />

Time will be formatted as 01:37

(Needed to display the Audio/Video file lengths.)

Thank you sooo much for this link!
Good...But...
This works great for static gridviews. However, how do you do such a thing with AutoGenerateColumns = true? How do you get the reference to the dynamic column to set the DataFormatString property
Thank You
Very clean and easy explanation ... thank you so much...
doesn't work for me
I tried the template column code <%# Bind("date_field", "dd-MMM-yyyy")%> and it still displays in regular format. I tried using a bunch of the canned formats with the same result, it's as if the code is being ignored completely.
good
It works fine thanks
Easy
Very easy to understand...
Thank You Very Much
Thank you
Thank you very much. Its useful to me. Very simple and clear explain.,
Another format
Thanks for the great article!

You can also combine the format patterns. For example, if you use "{0:MMM dd, yyyy}" your Date will be formatted as Mar 26, 2009.
Thanks!
This is exactly what I was looking for. It helped me fix all of my formatting problems.
helpful
It's very helpful, Thanks for posting this article
Error in Month Day
'm' is not Month day.
'm' - Represents the minute as a number from 0 through 59.
Good
Very neatly explained and
and the required formats neatly presented in a table ...
good for a quick reference
GREAT
Very nice code. But i how can i add date time contorl here.
Good!!
Thanks for the info!
Thanks
Very Nice!