09 Nov 2011

AutoGenerateColumns='true'的GridView如何支持htmlencode/htmldecode

我们知道BoundField.HtmlEncode 属性可以设置一个单元格是否能够htmlencode,我今天碰到的问题是:自动生成列的GridView,表头可能是包含html的比如<font color=red>邮件</font>,默认被htmlencode了,而我不希望这样做,所以有了如下的代码:

 

/// <summary>
/// Handles the PreRender event of the gvSource control.
/// </summary>
/// <param name=“sender”>The source of the event.</param>
/// <param name=“e”>The <see cref=“System.EventArgs”/> instance containing the event data.</param>
protected void gvSource_PreRender( object sender , EventArgs e )
{
    GridView gridView = sender as GridView;
    if ( gridView != null && gridView.HeaderRow != null && gridView.HeaderRow.Cells != null )
    {
        for ( int j = 0 ; j < gridView.HeaderRow.Cells.Count ; j++ )
        {
            gridView.HeaderRow.Cells[j].Text = System.Web.HttpUtility.HtmlDecode( gridView.HeaderRow.Cells[j].Text );
        }
    }
}