net - how to set date format in gridview templatefield




How to change datagridview column date format when gridview has autogeneratecolumns=true (6)

.ToString("dd/MMM/yyyy") (assuming your data is DateTime type)

I am auto generating columns in gridview depending on search parameters, few columns will be added or removed.

Please suggest me a way to set the date format to dd-mmm-yyyy for entire column in gridview.

For now, I'm doing it using rowdatabound. It checks every row, So it takes time to show the results.

This is what I do in rowdatabound

if (e.Row.RowType == DataControlRowType.DataRow)
{
        System.Data.DataRowView dtview;
        DateTime dt;
        int intCounter;
        dtview = (DataRowView)e.Row.DataItem;

        for (intCounter = 0; intCounter <= dtview.Row.ItemArray.Length - 1; intCounter++)
        {
            if (dtview.Row.ItemArray[intCounter] is System.DateTime)
            {
                dt = (DateTime)dtview.Row.ItemArray[intCounter];
                e.Row.Cells[intCounter].Text = dt.ToString("dd-MMM-yyyy");
            }
        }
    }

This checks for all records and then changes based on condition.

But I want to do it better, just by identifying the column and change the date format for complete column.


Disclaimer: I haven't tried this myself, but it looks possible.

A GridView has a public property called ColumnsGenerator that has a type of IAutoFieldGenerator. This is the object that determines how the columns are generated.

There's already an implementation of IAutoFieldGenerator out there, the default one: GridViewColumnsGenerator. This is a public, non-sealed class, and you can derive a type from it.

The method you would have to override is this one:

public override List<AutoGeneratedField> CreateAutoGeneratedFields(
      object dataObject, Control control);

Note the output, a List<T> of AutoGeneratedField. AutoGeneratedField has a property called DataFormatString:

public override string DataFormatString { get; set; }

So all you'd have to do is override CreateAutoGeneratedFields, like this:

public class MyDerivedGridViewColumnsGenerator : GridViewColumnsGenerator
{
   public override List<AutoGeneratedField> CreateAutoGeneratedFields(
      object dataObject, Control control)
   {
       var list = base.CreatedAutoGeneratedFields(dataObject, control);
       foreach(var field in list)
       {
         if(field.DataType == typeof(DateTime))
             field.DataFormatString = "dd-MMM-yyyy";
       }
       return list;
   }
}

Now, I'm not clear on how the ColumnsGenerator property gets set, so you might have to do it in code. But that should be fairly simple, since GridViewColumnsGenerator has a parameterless constructor:

 // GridView myGridView;
 myGridView.ColumnsGenerator = new MyDerivedGridViewColumnsGenerator();

I would set it before you bind to the GridView, so it's in place when it's time to create the columns.


Just expounding on saille's answer here:

For a DateTime, format isn't an issue. A DateTime is actually the number of ticks counting up from midnight, January 1, 1 A.D. So, really, it's just a long. Formatting only becomes an issue when it comes time to convert it into a string. So, you'll have to go and take care of the formatting either when you pull it out of the data table and are ready to output it, or put it into the data table as a string (which I would not recommend, for flexibility purposes). The formatting can be done with the .ToString call on the DateTime that saille suggests, .ToString("dd/MMM/yyyy")


On the date field in your gridview:

<asp:Label id="lblDate" runat="server" Text='<%# Eval("YourDate", "{0:yyyy/MM/dd}") %>' />

if you are binding an DataTable to Grid then Write an extension method or link Query like

public static void ChangeDateFormat<T>(this DataColumn column, Func<object, T> conversion)
{
   foreach(DataRow row in column.Table.Rows)
   {
    row[column] = conversion(row[column]);
   }
}

And to call that Method

dataTable.Columns["DateColumanName"].ChangeDateFormat(
val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy"));

Actual Source code pulled from here
And also note you need check the existence of column and data type and the other checks to get rid of errors.

Hope it helps.


How to remove the time part in Datefield of my data in gridview

if you really want to do it from a string you can use substring_index

SELECT SUBSTRING_INDEX('2016-05-01 12:00:00 AM', ' ', 1);

sample

MariaDB [yourschema]> SELECT SUBSTRING_INDEX('2016-05-01 12:00:00 AM', ' ', 1);
+---------------------------------------------------+
| SUBSTRING_INDEX('2016-05-01 12:00:00 AM', ' ', 1) |
+---------------------------------------------------+
| 2016-05-01                                        |
+---------------------------------------------------+
1 row in set (0.00 sec)

MariaDB [yourschema]>

if you get the date from the database you can format it with DATE_FORMAT

SELECT DATE_FORMAT('2016-05-01 12:00:00 AM', '%Y-%m-%d');

sample

MariaDB [yourschema]> SELECT DATE_FORMAT('2016-05-01 12:00:00 AM', '%Y-%m-%d');
+---------------------------------------------------+
| DATE_FORMAT('2016-05-01 12:00:00 AM', '%Y-%m-%d') |
+---------------------------------------------------+
| 2016-05-01                                        |
+---------------------------------------------------+
1 row in set, 1 warning (0.00 sec)

MariaDB [yourschema]>