How To Set a Date Format In GridView Using ASP.NET 2.0
(Using HtmlEncode Property)
(AKA, the DataFormatString=”{0:M-dd-yyyy}” Problem)
A very common desire is to set a column of a gridview to display just the month, day and year of a DateTime type. The problem is the by default, the HtmlEncode property of the boundfield attribute ( <asp:boundfield …) is set to True. The reason for this (as pointed out in the documentation of this attribute) is that this helps prevent cross-site scripting attacks and malicious content from being displayed. Microsoft recommends that the HtmlEncode attribute be enabled whenever possible.
The problem is that if this field is enabled, you can not pass format information to the boundfield control. That is, if you try the following code, you will not get the desired result.
<asp :GridView ID="GridView1" runat="server">
<columns>
<asp :BoundField DataField="CreationDate"
DataFormatString="{0:M-dd-yyyy}"
HeaderText="CreationDate" />
</columns>
</asp>
You have two choices to make this work as you would expect. The first choice is to simply set HtmlEncode to false as follows:
<asp :GridView ID="GridView1" runat="server">
<columns>
<asp :BoundField DataField="CreationDate"
DataFormatString="{0:M-dd-yyyy}"
HtmlEncode="false"
HeaderText="CreationDate" />
</columns>
</asp>
The second choice is to make the column a template and simply set the format string directly in the Label or Text Fields as follows.
<asp :GridView ID="GridView3" runat="server" >
<columns>
<asp :TemplateField HeaderText="CreationDate" >
<edititemtemplate>
<asp :Label ID="Label1" runat="server"
Text='<%# Eval("CreationDate", "{0:M-dd-yyyy}") %>'>
</asp>
</edititemtemplate>
<itemtemplate>
<asp :Label ID="Label1" runat="server"
Text='<%# Bind("CreationDate", "{0:M-dd-yyyy}") %>'>
</asp>
</itemtemplate>
</asp>
</columns>
</asp>
Below is a screen shot of what the three scenarios discussed above look like.
Good luck with your coding and hopefully, this will be one nasty you can put behind you.












June 22nd, 2006 at 2:34 am
Than You very much about your explaining. it works
July 7th, 2006 at 10:43 am
Thanks this was helpful to me.
July 10th, 2006 at 12:56 pm
Nice article. I like how you demonstrate in a couple different ways, cheers.
July 11th, 2006 at 3:42 am
Peter,
Thanks for this – was driving me mad !
Rgds, Peter
August 9th, 2006 at 6:07 am
What if I dynamically bind data to the gridview?
August 25th, 2006 at 7:17 pm
its very very helpfull..tq for that…
August 29th, 2006 at 2:56 am
Thank you!
September 13th, 2006 at 3:00 am
fantastic ! This code work
Thanks man
September 13th, 2006 at 5:06 am
It is very great it work in my project.
Thanks you very much…
September 25th, 2006 at 10:11 pm
Nice work Peter,
thanks.
October 10th, 2006 at 6:24 am
Helped me out, thanks.
November 17th, 2006 at 12:56 pm
thanks a lot man. it was very helpful.
November 17th, 2006 at 1:11 pm
I have to join in with all the other kudo’s — this simple problem was very irritating — thanks for the complete explanation.
November 24th, 2006 at 1:24 am
Thanks very usefful code. any way to format the bind text with a custom function?
December 1st, 2006 at 8:01 pm
Thanks! Nice work!
December 4th, 2006 at 9:07 pm
Nice, thanks
December 19th, 2006 at 11:44 am
Thanks, it helped.
January 18th, 2007 at 8:00 am
Thanks!Thanks!Thanks!Thanks!
very nice, thanks!
January 25th, 2007 at 3:52 pm
I have GridView binding to BLL object returning ArrayList.
How can I set DataFormatString programatically using GridView’s DataBinding or DataBound event?
Desing time it works.
DataFormatString of (###) ###-#### will work with formatting phone numbers in column?
January 30th, 2007 at 2:43 pm
Great stuff, thanks.
January 31st, 2007 at 5:14 am
help..HtmlEncode statement is not recognized
February 2nd, 2007 at 8:01 pm
Very useful! Thank a lot!
February 5th, 2007 at 7:21 am
very helpful, thankyou.
February 16th, 2007 at 2:44 am
nice try.
u got me out of a crappy situation
thank u!
February 28th, 2007 at 10:23 am
Bravo, Peter, this was great help!
Merci beau coup.
April 3rd, 2007 at 11:11 pm
Thanks,Its really Useful.
April 22nd, 2007 at 2:25 am
Thank you so much, now I can stop having nightmares.
April 22nd, 2007 at 4:14 pm
This worked great for display, but when trying to update it throws – System.FormatException, String was not recognized as a valid DateTime, anyone with suggestions.
May 16th, 2007 at 8:36 pm
Well done peter
Thanks
May 17th, 2007 at 5:06 pm
Thanks so much! I was beating my head against the wall!!
May 25th, 2007 at 4:12 am
Great Job! thanks
May 29th, 2007 at 11:45 am
Vey helpful. Thanks
June 7th, 2007 at 4:37 am
how to bind in GridView custom DatePicker Control to Null Value.
Here is code.
—————————————
‘
CalendarFont-Names=”Arial” InitialText=”Select a Date” TextBoxWidth=”80″ AutoPosition=”True” CalendarOffsetX=”-200px” CalendarOffsetY=”25px” CalendarTheme=”None” CalendarWidth=”200px” CallbackEventReference=”" Culture=”Bulgarian (Bulgaria)” EnableDropShadow=”True” MaxDate=”9999-12-31″ MinDate=”" NextMonthText=”>” NoneButtonText=”None” ShowNoneButton=”True” ShowTodayButton=”True” ZIndex=”1″>
‘>
—————————————-
September 7th, 2007 at 8:02 am
Thanks for your insightful article.
Warmest Regards
September 18th, 2007 at 1:50 am
How to do this if dynamically binding data in code behind?
October 4th, 2007 at 2:35 am
Thanks man, this is that i’m looking for.
October 16th, 2007 at 2:24 pm
Why is this not working for me I have done exactly what was explained
October 18th, 2007 at 11:50 pm
Thanks man, it worked for me too !!!
October 19th, 2007 at 7:07 am
hmmm coool
November 7th, 2007 at 1:53 pm
Good article, but the HtmlEncode=”False” isn’t doing the trick for me. I’m trying to dynamically bind to a GridView with the following code:
Dim gv As New GridView()
gv.DataSource = dt
gv.AutoGenerateColumns = False
For Each col As Data.DataColumn In dt.Columns
Dim myBoundField As New BoundField()
With myBoundField
Select Case col.ColumnName
Case “DtReadingFrom”
.HeaderText = “Start Date”
.DataFormatString = “{0:MM/dd/yyyy}”
.HtmlEncode = False
Case “DtReadingTo”
.HeaderText = “End Date”
.DataFormatString = “{0:MM/dd/yyyy}”
.HtmlEncode = False
Case “TX_METER_NUMBER”
.HeaderText = “Meter #”
Case Else
.HeaderText = col.ColumnName
End Select
.DataField = col.ColumnName
.Visible = True
End With
gv.Columns.Add(myBoundField)
Next
February 21st, 2008 at 1:36 pm
i just want to share with you mine experience. i tried to bind to objectdatasource where property was another custom object which implemented IFormatter. in this case you must ensure that ToString() doesnt return empty string. crazy. i found that out by dissasembling the code of BoundField. i wish i could avoid this rant but code actually looks like it was written by very junior guy..
April 22nd, 2008 at 1:27 pm
Thanks! Exactly what I need.
May 19th, 2008 at 12:07 am
I tried below code
but didn’t work.
Table Column ‘Booking_Date’ is of ‘datatime’ type.
can anybody explain?
May 19th, 2008 at 12:08 am
I tried below code
“”
but didn’t work.
Table Column ‘Booking_Date’ is of ‘datatime’ type.
can anybody explain?
June 1st, 2008 at 6:12 am
10x a lot!!!
June 11th, 2008 at 8:19 am
Absolutely perfect – wonderfully explained thanks mate
July 29th, 2008 at 11:27 pm
Hello Sir,
How to show datetime like
DataFormatString = “{0:MM/dd/yyyy hh:mm:ss AM/PM}”
I tried this but it doesn’t work. I have to export it to excel with AM/PM.
Thanks,
Prashant V
August 5th, 2008 at 1:58 am
hello peterkellner
thanks for your explanation.
For @Vedpathak:
How to show datetime like
DataFormatString = “{0:MM/dd/yyyy hh:mm:ss AM/PM}”
==> try for expression:
DataFormatString ={0:MM/dd/yyyy hh:mm:ss tt}
It will display hour with AM or PM
Hope to help you.
August 27th, 2008 at 9:19 pm
thankz, i solve my problem…
September 22nd, 2008 at 4:25 pm
Does anyone know how I would format just the time? I tried:
<asp:TextBox ID=”TextBox2″ runat=”server” Text=”>
<asp:Label ID=”Label2″ runat=”server” Text=”>
but it doesn’t work. I just get a parcer error.
September 22nd, 2008 at 4:27 pm
Does anyone know how to format just the time? I tried: but it doesn’t work. I just get a parcer error.
October 20th, 2008 at 7:44 am
October 20th, 2008 at 7:45 am
November 25th, 2008 at 2:44 pm
great work. solved my problem. thanks alot
November 26th, 2008 at 1:03 am
Superb man !!!!
It wrks excellent….
thnx man …
December 11th, 2008 at 11:00 am
i would say thanks for your help,
it certainly saved my time to formate the date in grid view.
cheers,
January 6th, 2009 at 6:19 am
Hooray………………….
IT worked ………..
Thanks alot ………
U Rockzzz………….
January 9th, 2009 at 1:24 am
To Nic Smith:
You can format just the date with DataFormatString=”{0:hh:mm:ss tt}” Notice lowercase ‘mm’. Upper case will give months while lowercase will give minutes. It worked for me.
January 26th, 2009 at 6:02 pm
Thanks a lot! This is awesome.
My question is, if I want to let the user rather than change that text, but give a calendar for them to choose from. How do I do that? I tried the Calendar object, but I could not get it to work.
That is like… they have the currently chosen date in a label or textfield, then next to it a button (like with an hourglass or somethin) that when they press that, a mini calenday pops up, and they can select the date from there.
January 31st, 2009 at 4:26 am
patrick: if u’r using asp.net..ajax control extensions has ur answer..
http://www.asp.net/learn/ajax-videos/video-124.aspx
March 24th, 2009 at 1:16 am
Thanks your code really works very well.
May 20th, 2009 at 10:03 pm
Cool.. This code Work’s Thks man..!!
May 22nd, 2009 at 3:11 am
This article very use full i got my desird soltion on it which i want immediatlty
Thanks
June 22nd, 2009 at 12:46 am
Thank U Very Much!!
U Rock!!!!!!
July 11th, 2009 at 10:55 am
Gr8 job!!
July 14th, 2009 at 11:07 pm
it works for me .thanks
August 18th, 2009 at 9:55 am
Great tip ive been trying everything for the last few hours.
worked perfect for my project
but a 10 second google search saved the day cheers
August 30th, 2009 at 3:42 am
Is not spam, it is only my commercial offer. Sorry if i mistake of topic!
Buy Clomid – Best testimonials. Buy now. Satisfaction is guaranteed.
Best price for brand and generic medications.
From $0.60 per item. Free Airmail shipping for Clomid 100mg 90 tabs and save $135 on order!
September 16th, 2009 at 11:06 pm
thank you very much realy
October 1st, 2009 at 9:50 pm
thanks a lot.. was searching for this so long…
October 10th, 2009 at 5:26 am
Thanks a lot!!!!!!!!!!
Its really helps to me
October 19th, 2009 at 5:11 am
hi,
how can i trim string using format?
November 3rd, 2009 at 5:24 am
thanks…………..
November 20th, 2009 at 5:41 am
Thank you for this tip. It saved me some time.
December 2nd, 2009 at 9:39 pm
Nice tips. I twill be more helpfull to all
December 4th, 2009 at 12:15 pm
This does not work when you bind a gridview to a collection when the column is a date.
January 4th, 2010 at 12:42 pm
Need help to format Phone Number.
The following code displays the phone number as 10 digits with no space.
What am I missing?
January 4th, 2010 at 12:43 pm
It did not display the code here it is one more time:
BoundField DataField=”oContactPhone” HeaderText=”Contact Phone”
ReadOnly=”True” SortExpression=”oContactPhone”
DataFormatString=”{0:(###) ###-####}”
HtmlEncode=”False”
January 18th, 2010 at 4:20 pm
Thanks for a simple answer with practical examples. Much preferred to wading through all the specific date formats in MSDN.
January 26th, 2010 at 9:29 am
can somebody show me how to format it from the codebehind? thanks
February 5th, 2010 at 11:31 am
its helped me out for my work
Thanks
February 6th, 2010 at 11:01 pm
Very good artical thanks 4 d post…
March 10th, 2010 at 8:16 am
very helpful!!!
I was after the “tt” piece. Many Thanks. NOTE: lowercase tt produces uppercase AM PM – thoughts on how to produce lowercase am pm?