Sunday, January 21, 2007

Dynamically generated gridview DateTime column formatting

One of the common questions that are being asked often is about formatting DateTime column in a grid view when the columns are auto-generated. Couple of easy solutions come to my mind are:



If using bound columns then it can be done by setting the DateTimeFormatting property like:

<asp:BoundField HeaderText="Start Date" DataField="START_DATE" SortExpression="START_DATE"

DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="false">

<ItemStyle HorizontalAlign="Left" />

</asp:BoundField>



If that’s not the case and we have no column specification done at design time then a work-around could be done using RowDataBound event; like:

protected void gvPSM_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowIndex >= 0)

{

#region "Date Formatting"

DateTime tempDate;

for (int cellNum = 0; cellNum < e.Row.Cells.Count; cellNum++)

{

try

{

// If it's datetime column then parsing works

tempDate = DateTime.Parse(e.Row.Cells[cellNum].Text);

e.Row.Cells[cellNum].Text = string.Format("{0:MM/dd/yyyy}", tempDate);

}

catch

{

// Do Nothing... it's not datetime column

}

}

#endregion "Date Formatting"

}

}



Love coding!

No comments: