Friday, April 28, 2006

 

BoundField.DataFormatString does not handle DateTime formatting

BoundField.DataFormatString does not handle DateTime formatting. If you would like to set the format for a DateTime field -- say displaying the date with only "{0:d}" you've got to set an additional parameter: HtmlEncode = false.

So, if you're creating things on the fly:

BoundField aColumn = new BoundField();
aColumn.DataField = "MyDateField";
aColumn.DataFormatString = "{0:d}";
aColumn.HtmlEncode = false;

GridView aGrid = new GridView();
aGrid.Columns.Add( aColumn );

This is not earth-shattering news. Raj Kaimal and others reported it much earlier. Raj notes that the BoundField applies HTML encoding before the data formatting. That makes sense.

What was most frustrating about this -- and consequently caused me to burn time -- is that the decision to apply HTML encoding before data formatting is NOT consistent across server controls. It's not even consistent among the classes that extend the DataCountrolField class.

In one of the CompositeControls that I've constructed I have a GridView that holds data that is generally unique by date. To save space I chose to create place the date into a ButtonField and let the ButtonField trigger the "Select" command:

ButtonField aColumn = new ButtonField();
aColumn.ButtonType = ButtonType.Link;
aColumn.DataTextField = "MyDateField";
aColumn.HeaderText = "MyHeaderText";
aColumn.CommandName = "Select";
aColumn.DataFormatString = "{0:d};

GridView aGrid = new GridView();
aGrid.Columns.Add( aColumn);

Guess what... this works! It just so happens that I tried this before I tried formatting the BoundColumn so I really thought I was screwing up the latter somehow.

So, which one is the buggy control, BoundField or ButtonField???

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?