C# – Link in a DataRow (Datatable)

cdatarowdatatablegridview

I'm building a DataTable dynamically and I'm trying to add a "link" in the DataRow(s) that I'm adding to the DataTable. The DataTable is bound to a GridView after it's creation.

Something like that :

   DataTable dataTable = new DataTable();
   foreach (Item item in items)
    {
        DataRow row = dataTable.NewRow();
        dataTable.Columns.Add(new DataColumn("col"));

        row["col"] = "<a href='http://www.google.com'>Link here</a>";

        dataTable.Rows.Add(row);

    }

Then I bind it to a GridView :

        <asp:GridView ID="grdView" Runat="server" border="0" EnableViewState="true" style="width:100%;"
            AutoGenerateColumns="true" AllowPaging="false" PagerSettings-Visible="false" 
            ShowHeader="true" ShowFooter="true" CellPadding="0" CellSpacing="0"
            Visible="True">
        </asp:GridView>

But the HTML in the Column is encoded when I bind it to the GridView.
Is there a way to add a HyperLink object there or something like that?

P.S. It's not in the example but the columns are added dynamically (it means that I don't know before the rendering how many columns I'll have)

UPDATE #1

I have access to the GridView when I create the columns.
I was able to do something like that :

    dataTable.Columns.Add(new DataColumn("col"));

    BoundField bf = new BoundField();
    bf.HtmlEncode = false;
    bf.DataField = "col";
    grd.Columns.Add(bf);

   row["col"] = "<a href='http://www.google.com'>Link here</a>";

But it displays 2 coloumns "col"…

UPDATE #3 :
I used a DataGrid instead. It doesn't encode HTML when inserted in "plain text" in the data rows.

Best Answer

If you are returning html code from your query, just use htmlEncode=False on your boundfield. Also set AutoGenerateColumns="false" on your gridview, that's why you're getting double columns on your gridview.

Related Topic