ASP.NET HyperLink in GridView using HyperLinkField, SqlDataSource, BoundField, TemplateField, and HyperLink

I am amazed how difficult it was to find simple examples of exposing a hyperlink in an asp.net gridview control. I tried some obvious things that didn’t work at first, but I got four different approaches working that I thought I would share for others that run into this [I would assume] common need.

In my case, I wanted to hyperlink to an external site based, passing in the external url along with an ID passed in as a URL parameter.

For example: http://www.externalsite.com?myID=1234

Construct URL Inside SQL

This is old code that had the SQL query inside a SqlDataSource control, so I first thought of just adding the column there:

SELECT '<a href=&quot;http://www.externalsite.com?myID=' + CONVERT(VARCHAR,MY_FIELD) + '&quot;>Link</a>' Link, ...

By default, this rendered the actual HTML encoded hyperlink inside the grid: Link

This was easily remedied by either of the following approaches:

<Columns>
<asp:BoundField HtmlEncode="false" DataField="Link" HeaderText="Link" SortExpression="Link" />
</Columns>

Note: The key here is HtmlEncode="false"

<Columns>
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<%# Eval ("Link") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>

Construct URL Outside of SQL

The other two approaches do not rely on the URL being generated inside the SQL, but instead leveraging the ObjectId when constructing the URL in the GridView:

<Columns>
<asp:HyperLinkField Text="Link" Target="_blank" DataNavigateUrlFields="ObjectId" DataNavigateUrlFormatString="http://www.externalsite.com?myID={0}" />
</Columns>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" Text="Link" Target="_blank" NavigateUrl='<%# "http://www.externalsite.com?myID=" + Eval("ObjectId")%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>

2 Comments on “ASP.NET HyperLink in GridView using HyperLinkField, SqlDataSource, BoundField, TemplateField, and HyperLink”

Leave a Reply

Your email address will not be published. Required fields are marked *