Using Hyperlink columns in GridView

Waqas Anwar
30 March 2008
41132 Views

GridView control is one of the most powerful controls in ASP.NET 2.0. This control displays database records in typical tabular form, and provides features such as Sorting, Paging, Selection and Editing without writing a single line of code. It also has many different types of fields (columns) such as hyperlinks, images, checkboxes etc.

In the following tutorial, I will show you different techniques you can use to display hyperlinks in GridView.  For this tutorial I am using Microsoft famous sample database Northwind and I am joining Products and Suppliers tables to display ProductID, ProductName, UnitPrice, SupplierID and CompanyName in the GridView. 


hyperlink_fields.gif



Databound hyperlink text with dynamic query string URL

<asp:HyperLinkField 
      DataTextField="ProductName" 
      HeaderText="Product Name" 
      SortExpression="ProductName" 
      DataNavigateUrlFields="ProductID" 
      DataNavigateUrlFormatString="ProductDetails.aspx?ProductID={0}" />


Databound hyperlink text with multiple fields in the query string URL

<asp:HyperLinkField 
      DataNavigateUrlFields="SupplierID, CompanyName" 
      DataNavigateUrlFormatString="SupplierDetails.aspx?SupplierID={0}&CompanyName={1}"
      DataTextField="CompanyName" 
      HeaderText="Supplier" 
      SortExpression="CompanyName" />
                   

Static hyperlink text with dynamic query string URL
 
<asp:HyperLinkField 
      DataNavigateUrlFields="ProductID" 
      DataNavigateUrlFormatString="ProductDetails.aspx?ProductID={0}"
      HeaderText="View Details" 
      SortExpression="ProductName" 
      Text="View Details" />


Static hyperlink text with external URL opening in new browser window

<asp:HyperLinkField 
      Text="Amazon" 
      NavigateUrl="http://www.amazon.com/
      HeaderText="Search Online" 
      Target="_blank" />


Databound hyperlink text with custom format to display link text
 
<asp:HyperLinkField 
      DataTextField="UnitPrice" 
      DataTextFormatString="GBP {0}" 
      DataNavigateUrlFields="ProductID" HeaderText="Unit Price"
      DataNavigateUrlFormatString="ProductDetails.aspx?ProductID={0}"   />