How to display only date in GridView when pulling data from a DB? C#

28,159

Solution 1

in the grid view of yours add the property called DataFormatString

DataFormatString examples:


{0:dd MMMM yyyy}    -    gives 24 February 2006
{0:MMM dd}          -    gives Feb 24 (substitue MMM with MMMM for the full month name 
                         instead of abbreviation) 
{0:dd/MM/yy}        -    gives 24/02/06 
{0:dd/MM/yyyy}      -    gives 24/02/2006

Sample Code

<asp:BoundField HeaderText="Date" 
                DataField="SampleDate" 
                DataFormatString="{0:MM/dd/yyyy}"  >

MSDN BoundField.DataFormatString Property

Solution 2

You just need to set the dataformatstring with how you want it to be populated.

As exemplified on the MSDN page:

Money:

<asp:BoundColumn HeaderText="Price" DataField="Price"
                                     DataFormatString="{0:c}" />

With the {0:c}, placing a number after the c value (such as {0:c2}) will give you that many decimal places.

Date:

<asp:boundfield datafield="MyDate" dataformatstring="{0:MM/dd/yyyy}" />
Share:
28,159
SS113
Author by

SS113

Updated on February 01, 2020

Comments

  • SS113
    SS113 over 4 years

    I am pulling data from an access database to show in a GridView control on a ASP.NET project. It works fine but I want to see if I can format the data that is being pulled. Currently any currency is being truncated from xx.xx to just the dollar amounts. Also the dates are displaying mm/dd/yyyy hh/mm/ss AM/PM

    I tried editing the database itself to the right values (I set the currency field to "Currency" and the date field to "Short Date" but when I pull that date it still shows them not formatted.

    EDIT: Sorry, had to take the code down

    Any ideas? Thank you

  • SS113
    SS113 over 10 years
    Thanks! This works great but now I'm getting the formatted columns and next to them another set from the code generated columns that are unformatted. Code I used: <asp:BoundField DataField="PayRate" HeaderText="Rate" SortExpression="PayRate" DataFormatString="{0:C}" />
  • SS113
    SS113 over 10 years
    Amarnath, I'm not getting any errors but duplicate columns such as: goo.gl/BVbprD
  • Amarnath Balasubramanian
    Amarnath Balasubramanian over 10 years
    add autogeneratecolumns in the grid to false this property is to be added after the ID of the GridView
  • Martin Braun
    Martin Braun over 7 years
    Use DataFormatString="{0:d}" to localize it for any culture.