(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.
<columns> <asp headertext="CreationDate" dataformatstring="{0:M-dd-yyyy}" datafield="CreationDate" :BoundField /></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 id="GridView1" runat="server" :GridView><columns> <asp headertext="CreationDate" dataformatstring="{0:M-dd-yyyy}" datafield="CreationDate" :BoundField HtmlEncode="false" /></columns>
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 id="GridView3" runat="server" :GridView> <columns> <asp headertext="CreationDate" :TemplateField> <edititemtemplate> <asp id="Label1" runat="server" Label.Text='<%# Eval("CreationDate", "{0:M-dd-yyyy}") %>'> </asp> </edititemtemplate> <itemtemplate> <asp id="Label1" runat="server" Label.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…
April 29th, 2010 at 1:53 am
Thanks, was helpful.
May 3rd, 2010 at 6:24 am
hey many thanks !!
May 13th, 2010 at 1:08 pm
Thanks very much for a clear explanation and an easy solution! Nicely documented and easy to follow. Your help is much appreciated!
May 19th, 2010 at 8:26 am
Thank you…really helps and saves lot of my time…..
June 3rd, 2010 at 8:49 am
Thanks..! Its gave a path to build stable scheduler for my client.
June 4th, 2010 at 5:31 am
Thanks. it’s really solve my problem & save my time.
June 4th, 2010 at 5:32 am
Thanks. it’s really solve my problem.
June 15th, 2010 at 11:43 pm
Thanks a lot
Its really helps to me
Happy Coding
June 15th, 2010 at 11:44 pm
Thanks a lot
Its really helps to me
August 11th, 2010 at 7:04 am
I can change the DateFormatString in the BoundField Properties and my display results reflect the change.
I am not sure why you say this cannot be accomplished.
Perhaps, Microsoft corrected the issue since your post.
Additionally, I do not see how the following is permitted:
VS throws an error for this code and rightfully so.
I guess as long as we find an appropriate solution then we are happy.
Best Regards,
Richard
August 17th, 2010 at 3:16 am
use “{0:D}” output sample =14 Agustus 2010
September 4th, 2010 at 2:23 pm
mehrbani janab
September 22nd, 2010 at 5:26 pm
Yes, learn, and very helpful.
October 4th, 2010 at 2:14 pm
Just what I was looking for – thank you.
October 13th, 2010 at 7:47 am
need to apply this formatting to a templatefield that is bound dynamically …any ideas? Not an option do this formatting in mark-up…needs to happen in code behind.
thanks in advance
November 3rd, 2010 at 6:39 am
For Null Values how can we set some default value ???
November 4th, 2010 at 8:35 am
[...] post is inspired by another post on did on GridView date formatting years ago. It’s still very [...]
November 29th, 2010 at 10:51 pm
Thanks man…
December 1st, 2010 at 5:18 am
Thanks for great contribution, clear and concise
December 1st, 2010 at 5:22 am
Nice and practical! But can you please illustrate formatting numbers? Like into fewer decimal places.. i tried ” and it is not resulting the expected.
Thanks Much
December 2nd, 2010 at 11:07 pm
Thanks a lot.. i got how to publish only date in grid view…
December 15th, 2010 at 8:55 am
THXX A LOOTTTT!!!! >.<
i look for this since 10 hours ago.. LOL
January 10th, 2011 at 1:36 am
I usually format the cells in the RowDataBound in the code behind. This method seems quite easy and straight forward
Thank you
February 23rd, 2011 at 2:37 am
Thanks.. its works superb.
March 11th, 2011 at 7:08 am
Yei! thanks
March 14th, 2011 at 9:19 am
This code works very well on my local computer. I’ve tested the entire script and seems to work fine. Thank you !
April 14th, 2011 at 12:15 pm
Thanks a lot sir…
I was stuck at that for a long time ………….
April 20th, 2011 at 7:24 pm
thanks
April 25th, 2011 at 1:29 am
Peter,
Thanks for this – was driving me mad !
Rgds, Peter
April 29th, 2011 at 2:00 am
lead to this page with google, the gridview date format bothering me for a long time. thx 4 yr valuable share.
May 2nd, 2011 at 6:51 am
Definitely believe that which you stated. Your favorite justification seemed to be on the web the simplest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they plainly don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people can take a signal. Will probably be back to get more. Thanks
May 6th, 2011 at 3:00 am
Web design is a hard lesson for me. Still need to learn more…
May 12th, 2011 at 8:36 am
Thanks, I remember in the early days with classic ASP, using a gridview was a nightmare!
May 19th, 2011 at 7:19 pm
Very nice initiative!
June 21st, 2011 at 9:29 am
thanks a ton!! helped in my project
August 4th, 2011 at 12:11 am
Thank you so much for example
September 20th, 2011 at 8:28 am
Thanks for lot.. it is really useful article..
October 1st, 2011 at 6:30 am
For those who are having problems with date field updates (getting incorrect string format etc error messages) I’ll suggest not using template field. Instead use boundfield such as:
October 1st, 2011 at 6:35 am
And if you want the dating format to be applied during editing as well add this extra setting to the control:
ApplyFormatInEditMode=”True”
The code sample I had added to my previous message has somehow dissapeared. It was like below (I encoded it hoping it will display this time)
%3Casp%3ABoundField%20DataField%3D%22dPayment%22%20DataFormatString%3D%22%7B0%3Ad%7D%22%20HeaderText%3D%22Payment%22%20SortExpression%3D%22dPayment%22%20ApplyFormatInEditMode%3D%22True%22%20%3E
October 1st, 2011 at 6:37 am
Sorry for multiple messages but I had to find a way to put the example code
October 12th, 2011 at 4:14 am
Thanks you so much for the help
December 10th, 2011 at 3:34 am
Thanks men
December 19th, 2011 at 12:07 am
thanks you.
December 31st, 2011 at 12:59 am
Thanks. It works well.
March 16th, 2012 at 4:03 am
Thanks for date format it help me a lot
April 6th, 2012 at 1:05 am
very nice