views:

533

answers:

2

I have a GridView bound to a DataTable that I construct. Most columns in the table contain the raw HTML for a hypelinklink, and I would like that HTML to render as a link in the browser, but the GridView is automatically encoding the HTML, so it renders as markup.

How can I avoid this without explicitly adding HyperLink, or any other, columns?

+4  A: 

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, deconde 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);
}
Jørn Schou-Rode
I want to do this for auto-generated columns, not explicit columns.
ProfK
@ProfK: I am sorry I missed that `AutoGenerateColumns = true`. I have now updated my question to answer the actual question.
Jørn Schou-Rode
A: 

Well since the html for the link is in your db already, you could just output the html to a literal control.

<asp:TemplateField HeaderText="myLink" SortExpression="myLink">
    <ItemTemplate>
        <asp:Literal ID="litHyperLink" runat="server" Text='<%# Bind("myLink", "{0}") %>' />
    </ItemTemplate>
</asp:TemplateField>

This should render your link as raw text allowing the browser to render it as the link you expect it to be.

Joel Etherton