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.
- Posted in .Net 2.0, ASP.NET 2.0  




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

  1. ozan Windows XP Internet Explorer 6.0 Says:

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

  2. Chris Windows XP Internet Explorer 7.0 Says:

    Thanks this was helpful to me.

  3. Nick Windows XP Mozilla Firefox 1.5.0.4 Says:

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

  4. Peter Windows XP Mozilla Firefox 1.5.0.4 Says:

    Peter,

    Thanks for this - was driving me mad !

    Rgds, Peter

  5. Jason Shaffer Windows XP Internet Explorer 6.0 Says:

    What if I dynamically bind data to the gridview?

  6. fiza Windows XP Internet Explorer 6.0 Says:

    its very very helpfull..tq for that…

  7. De Block Maarten Windows XP Mozilla Firefox 1.5.0.6 Says:

    Thank you!

  8. Sarfaraj Sayyad Windows XP Internet Explorer 6.0 Says:

    fantastic ! This code work
    Thanks man

  9. Viral Windows XP Internet Explorer 6.0 Says:

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

  10. Daren Windows Server 2003 Mozilla Firefox 1.5.0.7 Says:

    Nice work Peter,

    thanks.

  11. Isen Windows XP Internet Explorer 6.0 Says:

    Helped me out, thanks.

  12. Jay K Windows Server 2003 Internet Explorer 6.0 Says:

    thanks a lot man. it was very helpful.

  13. Chris Windows XP Internet Explorer 6.0 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 Windows XP Mozilla Firefox 2.0 Says:

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

  15. Vladimir Windows XP Mozilla Firefox 2.0 Says:

    Thanks! Nice work!

  16. Fawad Windows 2000 Mozilla Firefox 2.0 Says:

    Nice, thanks

  17. Dmitriy K Windows XP Mozilla Firefox 2.0.0.1 Says:

    Great stuff, thanks.

  18. beginer Windows XP Internet Explorer 6.0 Says:

    help..HtmlEncode statement is not recognized

  19. Ruby Windows 2000 Internet Explorer 6.0 Says:

    Very useful! Thank a lot!

  20. Rajan Windows XP Opera 9.10 Says:

    very helpful, thankyou.

  21. kburn Windows XP Mozilla Firefox 2.0.0.1 Says:

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

    thank u!

  22. Uncle Lar Windows XP Internet Explorer 7.0 Says:

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

  23. shrish Windows XP Mozilla Firefox 2.0.0.3 Says:

    Thanks,Its really Useful.

  24. ThinkTank Windows XP Mozilla Firefox 2.0.0.3 Says:

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

  25. Tome Windows Vista Internet Explorer 7.0 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.

  26. Asmat Khan Windows XP Mozilla Firefox 2.0.0.3 Says:

    Well done peter
    Thanks

  27. John Uhrich Windows XP Internet Explorer 6.0 Says:

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

  28. Zero Windows XP Internet Explorer 7.0 Says:

    Great Job! thanks

  29. Bernie Windows XP Internet Explorer 6.0 Says:

    Vey helpful. Thanks

  30. Mihail Windows XP Internet Explorer 7.0 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″>

    ‘>

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

  31. Prashant Windows XP Mozilla Firefox 2.0.0.6 Says:

    Thanks for your insightful article.
    Warmest Regards

  32. Danny Windows XP Internet Explorer 7.0 Says:

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

  33. Kusno Windows 2000 Internet Explorer 6.0 Says:

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

  34. Paula Windows XP Internet Explorer 6.0 Says:

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

  35. Amitabh Windows Server 2003 Internet Explorer 7.0 Says:

    Thanks man, it worked for me too !!!

  36. int Windows XP Internet Explorer 7.0 Says:

    hmmm coool

  37. Nick Windows XP Mozilla Firefox 2.0.0.9 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

  38. naraga Windows Server 2003 Mozilla Firefox 2.0.0.12 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..

  39. Eric Windows XP Mozilla Firefox 2.0.0.11 Says:

    Thanks! Exactly what I need.

  40. gaurav Windows XP Internet Explorer 7.0 Says:

    I tried below code

    “”

    but didn’t work.

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

    can anybody explain?

  41. rachel Windows XP Mozilla Firefox 2.0.0.14 Says:

    10x a lot!!!

  42. Xcalibur Windows Vista Internet Explorer 7.0 Says:

    Absolutely perfect - wonderfully explained thanks mate

Leave a Reply