Tuesday, July 15, 2008

DataFormatString not working in GridView!

I've spent about half an hour trying to determine why the DataFormatString format would not be applied to cell values in a GridView. The short answer: set the HtmlEncode property of the BoundField to false!

Now for the long answer:

A while ago I wrote a small article about how to format the data in your autogenerated GridView columns. At the end of the post I added a small update that explained why I set the HtmlEncode to false. It was, in my opinion, a GridView bug.

However, I didn't realise at the time that the same thing applies to normal GridView BoundFields as well. The thing is, in order to display a value in a bound cell, it FIRST applies the HtmlEncoding to the value CAST TO STRING, THEN it applies the FORMATTING. Here is the reflected source:


/// <summary>Formats the specified field value for a cell in the <see cref="T:System.Web.UI.WebControls.BoundField"></see> object.</summary>
/// <returns>The field value converted to the format specified by <see cref="P:System.Web.UI.WebControls.BoundField.DataFormatString"></see>.</returns>
/// <param name="dataValue">The field value to format.</param>
/// <param name="encode">true to encode the value; otherwise, false.</param>
protected virtual string FormatDataValue(object dataValue, bool encode)
{
string text1 = string.Empty;
if (!DataBinder.IsNull(dataValue))
{
string text2 = dataValue.ToString();
string text3 = this.DataFormatString;
int num1 = text2.Length;
if ((num1 > 0) && encode)
{
text2 = HttpUtility.HtmlEncode(text2);
}
if ((num1 == 0) && this.ConvertEmptyStringToNull)
{
return this.NullDisplayText;
}
if (text3.Length == 0)
{
return text2;
}
if (encode)
{
return string.Format(CultureInfo.CurrentCulture, text3,
new object[] { text2 });
}
return string.Format(CultureInfo.CurrentCulture, text3,
new object[] { dataValue });
}
return this.NullDisplayText;
}


At least the method is virtual. As you can see, there is no way to format a DateTime, let's say, once it is in string format.

Therefore, if you ever want to format your data in a GridView by using DataFormatString, you should make sure HtmlEncode is set to false! Or at least create your own BoundField object that implements a better FormatDataValue method.

0 comments: