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.
Use
Eval
function to define string formation in aspx code:Complete Example:
Here's a fairly simple solution: rather than handle each row separately, set-up the columns before binding the grid.
In the following example,
view
is an object that generates a regularDataTable
and the grid view has itsAutoGenerateColumns
property set tofalse
.Essentially, you just examine the columns' data type and when its a
DateTime
, set the format you want.if you are binding an DataTable to Grid then Write an extension method or link Query like
And to call that Method
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.
I managed to format the values of an auto generated datetime column implementing the event ColumnAdded of the DataGridView:
I'm a little late. But this worked for me. It still uses the RowDataBound() method. But it only runs against the first row in the data source.
Disclaimer: I haven't tried this myself, but it looks possible.
A
GridView
has a public property calledColumnsGenerator
that has a type ofIAutoFieldGenerator
. 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:
Note the output, a List<T> of
AutoGeneratedField
.AutoGeneratedField
has a property calledDataFormatString
:So all you'd have to do is override
CreateAutoGeneratedFields
, like this: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, sinceGridViewColumnsGenerator
has a parameterless constructor:I would set it before you bind to the
GridView
, so it's in place when it's time to create the columns.