Prevent HTML encoding in auto-generated GridView columns

I was able to achieve this by using the solution that Jørn Schou-Rode provided, I modified a little bit to make it work from the RowDataBound Event of my Gridview.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
           for (int j = 0; j < e.Row.Cells.Count; j++) 
           {
               string encoded = e.Row.Cells[j].Text;
               e.Row.Cells[j].Text = Context.Server.HtmlDecode(encoded);
           }

    }
}

Simply set the BoundColumn.HtmlEncode property to false:

<asp:BoundField DataField="HtmlLink" HtmlEncode="false" />


I am afraid that there is no easy way to disable HTML encoding of the contents in a GridView with AutoGenerateColumns= true. However, I can think of two workarounds that might solve the problem you are facing:

Option 1: Inherit the GridView class, override the Render method, loop through all cells, decode their contents, before executing the base method:

for (int i = 0; i < Rows.Count; i++) 
{
    for (int j = 0; j < Rows[i].Cells.Count; j++) 
    {
        string encoded = Rows[i].Cells[j].Text;
        Rows[i].Cells[j].Text = Context.Server.HtmlDecode(encoded);
    }
}

Option 2: In a class inheriting from GridView or in the Page or Control using it, make your own inspection of the DataTable and create an explicit BoundColumn for each column:

foreach (DataColumn column in dataTable.Columns)
{
    GridViewColumn boundColumn = new BoundColumn
        {
            DataSource = column.ColumnName,
            HeaderText = column.ColumnName,
            HtmlEncode = false
        };
    gridView.Columns.Add(boundColumn);
}