Thursday, July 2, 2009

.NET asp:BoundField DataFormatString problem


To apply a DataFormatString on a BoundField like DataFormatString="{0:MM/dd/yyyy}
in older versions of .NET you need to set HtmlEncode="false". It doesn't seem to
be needed in 3.5. If you are going to allow editing also add
ApplyFormatInEditMode="true".

I decided to do this programmaticly because I am dealing with many reports (~8)
with lots of fields (28-53) that change often. There is one method for gridViews
and another for detailsView.

public static void gridViewFormatDates(GridView gv)
{
for (int i = 0; i < gv.Columns.Count; i++)
{
if (gv.Columns[i].GetType() == typeof(BoundField))
{
BoundField d = (BoundField)gv.Columns[i];
SqlDataSource sds = (SqlDataSource) gv.DataSourceObject;
if (gv.Columns[i].SortExpression.Contains("date"))
{
d.ApplyFormatInEditMode = true;
d.DataFormatString = "{0:MM/dd/yyyy}";
}
}
}
}

public static void detailsViewFormatDates(DetailsView dv)
{
for (int i = 0; i < dv.Fields.Count; i++)
{
if (dv.Fields[i].GetType() == typeof(BoundField))
{
BoundField d = (BoundField)dv.Fields[i];
if (dv.Fields[i].SortExpression.Contains("date"))
{
d.ApplyFormatInEditMode = true;
d.DataFormatString = "{0:MM/dd/yyyy}";
}
}
}
}

Ok you may have noticed that the fieldname (sortExpression) must have "date"
in it for this to work. Yeah it's ugly. So I came up with another solution
which still isn't perfect either.

I previously created a method to shorten long gridview columns. So I added
this automatic date formatting to it. Call this from your onrowcreated method
like gridViewShortenColumns(myGridView, e.Row, 30);

public static void gridViewShortenColumns(GridView gv, GridViewRow gvr, int width)
{
DataRowView dr = (DataRowView)gvr.DataItem;
for (int i = 0; i < gvr.Cells.Count; i++)
{
DataControlFieldCell d = (DataControlFieldCell)gvr.Cells[i];
String name = d.ContainingField.SortExpression;
if (!name.Equals("") && dr[name].GetType() == typeof(DateTime))
((BoundField)gv.Columns[i]).DataFormatString = "{0:MM/dd/yyyy}";
if (dr != null && name != null && !name.Equals("") &&
gvr != null && dr[name] != null && dr[name].ToString().Length > width)
{
gvr.Cells[i].ToolTip = dr[name].ToString();
dr[name] = dr[name].ToString().Substring(0, width) + " ...";
}
}
}

No comments:

Post a Comment