How To Set a Date Format In GridView Using ASP.NET 2.0(Using HtmlEncode Property)
Wednesday 24 May 2006 @ 11:57 am

How To Set a Date Format In GridView Using ASP.NET 2.0

(Using HtmlEncode Property)

(AKA, the DataFormatString=”{0:M-dd-yyyy}” Problem)

 

Add to Technorati Favorites

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.

Output of all three scenarios

 


Good luck with your coding and hopefully, this will be one nasty you can put behind you.



82 Responses to “How To Set a Date Format In GridView Using ASP.NET 2.0(Using HtmlEncode Property)”

  1. ozan Says:

    Than You very much about your explaining. it works :)

  2. Chris Says:

    Thanks this was helpful to me.

  3. Nick Says:

    Nice article. I like how you demonstrate in a couple different ways, cheers.

  4. Peter Says:

    Peter,

    Thanks for this – was driving me mad !

    Rgds, Peter

  5. Jason Shaffer Says:

    What if I dynamically bind data to the gridview?

  6. fiza Says:

    its very very helpfull..tq for that…

  7. De Block Maarten Says:

    Thank you!

  8. Sarfaraj Sayyad Says:

    fantastic ! This code work
    Thanks man

  9. Viral Says:

    It is very great it work in my project.
    Thanks you very much…

  10. Daren Says:

    Nice work Peter,

    thanks.

  11. Isen Says:

    Helped me out, thanks.

  12. Jay K Says:

    thanks a lot man. it was very helpful.

  13. Chris Says:

    I have to join in with all the other kudo’s — this simple problem was very irritating — thanks for the complete explanation.

  14. Ofertas de Empleo Says:

    Thanks very usefful code. any way to format the bind text with a custom function?

  15. Vladimir Says:

    Thanks! Nice work!

  16. Fawad Says:

    Nice, thanks

  17. McCulloch Says:

    Thanks, it helped.

  18. zahorjana Says:

    Thanks!Thanks!Thanks!Thanks!
    very nice, thanks!

  19. KD Says:

    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?

  20. Dmitriy K Says:

    Great stuff, thanks.

  21. beginer Says:

    help..HtmlEncode statement is not recognized

  22. Ruby Says:

    Very useful! Thank a lot!

  23. Rajan Says:

    very helpful, thankyou.

  24. kburn Says:

    nice try.
    u got me out of a crappy situation :P

    thank u!

  25. Uncle Lar Says:

    Bravo, Peter, this was great help!
    Merci beau coup.

  26. shrish Says:

    Thanks,Its really Useful.

  27. ThinkTank Says:

    Thank you so much, now I can stop having nightmares.

  28. Tome Says:

    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.

  29. Asmat Khan Says:

    Well done peter
    Thanks

  30. John Uhrich Says:

    Thanks so much! I was beating my head against the wall!!

  31. Zero Says:

    Great Job! thanks

  32. Bernie Says:

    Vey helpful. Thanks

  33. Mihail Says:

    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″>

    ‘>

    —————————————-

  34. Prashant Says:

    Thanks for your insightful article.
    Warmest Regards

  35. Danny Says:

    How to do this if dynamically binding data in code behind?

  36. Kusno Says:

    Thanks man, this is that i’m looking for.

  37. Paula Says:

    Why is this not working for me I have done exactly what was explained

  38. Amitabh Says:

    Thanks man, it worked for me too !!!

  39. int Says:

    hmmm coool

  40. Nick Says:

    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

  41. naraga Says:

    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..

  42. Eric Says:

    Thanks! Exactly what I need.

  43. gaurav Says:

    I tried below code

    but didn’t work.

    Table Column ‘Booking_Date’ is of ‘datatime’ type.

    can anybody explain?

  44. gaurav Says:

    I tried below code

    “”

    but didn’t work.

    Table Column ‘Booking_Date’ is of ‘datatime’ type.

    can anybody explain?

  45. rachel Says:

    10x a lot!!!

  46. Xcalibur Says:

    Absolutely perfect – wonderfully explained thanks mate

  47. Prashant Deepak Vedpathak Says:

    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

  48. hugo Says:

    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.

  49. bard Says:

    thankz, i solve my problem…

  50. Nic Smith Says:

    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.

  51. Nic Smith Says:

    Does anyone know how to format just the time? I tried: but it doesn’t work. I just get a parcer error.

  52. Shahid Says:

    :) :) superb

  53. Shahid Says:

    :)

  54. aslam Says:

    great work. solved my problem. thanks alot

  55. Dipesh Says:

    Superb man !!!!
    It wrks excellent….
    thnx man …

  56. Genious Says:

    i would say thanks for your help,

    it certainly saved my time to formate the date in grid view.

    cheers,

  57. Swaroop Says:

    Hooray………………….

    IT worked ………..

    Thanks alot ………

    U Rockzzz………….

  58. Digambar Says:

    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.

  59. patrick Says:

    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.

  60. Nida Says:

    patrick: if u’r using asp.net..ajax control extensions has ur answer..
    http://www.asp.net/learn/ajax-videos/video-124.aspx

  61. Teena Says:

    Thanks your code really works very well.

  62. Vamsi Says:

    Cool.. This code Work’s Thks man..!!

  63. Jitendra Tyagi Says:

    This article very use full i got my desird soltion on it which i want immediatlty

    Thanks

  64. Chandralekha Says:

    Thank U Very Much!!
    U Rock!!!!!!

  65. MJ Says:

    Gr8 job!!

  66. Akhtar jahan Says:

    it works for me .thanks

  67. mixdownx Says:

    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

  68. buyclomido Says:

    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!

  69. Ujwal Khairnar Says:

    thank you very much realy

  70. abhishoka Says:

    thanks a lot.. was searching for this so long…

  71. Shivani Khare(MCA) Says:

    Thanks a lot!!!!!!!!!!
    Its really helps to me

  72. Bilal Sammour Says:

    hi,
    how can i trim string using format?

  73. nadeeka Says:

    thanks…………..

  74. William Jordan Says:

    Thank you for this tip. It saved me some time.

  75. Just human Says:

    Nice tips. I twill be more helpfull to all

  76. MA Says:

    This does not work when you bind a gridview to a collection when the column is a date.

  77. George Rindov Says:

    Need help to format Phone Number.
    The following code displays the phone number as 10 digits with no space.

    What am I missing?

  78. George Rindov Says:

    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”

  79. Joel Says:

    Thanks for a simple answer with practical examples. Much preferred to wading through all the specific date formats in MSDN.

  80. campingmap Says:

    can somebody show me how to format it from the codebehind? thanks

  81. Vamsee Says:

    its helped me out for my work
    Thanks

  82. PT Sivakumar Says:

    Very good artical thanks 4 d post…

Leave a Reply