Wednesday, August 4, 2010

GridView and HyperLinkField

It’s been a while since I use the GridView control to display data and I just realize that I have never used the HyperLinkField to provide a link to another page with the data from the the database. Every time I needed to do so, I always use a TemplateField with an HyperLink control.

Well with the HyperLinkField, is so easy to provide a link with the data needed in query string! As an example, lets say I want to give a link to the user to display customer information from an order. We would have two web pages, one page showing the orders from the Northwind database and another page that display the customer information from an order. The customer information page will display the customer data from the customer id send via the query string parameter.

In the past, I would have used a TemplateField to provide a link for the customer information like this:
   1: <asp:TemplateField HeaderText="CustomerID" SortExpression="CustomerID">
   2:    <ItemTemplate>
   3:       <asp:HyperLink ID="HyperLink1" runat="server"
   4:          NavigateUrl='<%# "~/CustomerInfo.aspx?CustId=" 
   5:             + DataBinder.Eval(Container.DataItem, "CustomerID") %>'
   6:          Text='<%# Bind("CustomerID") %>' Target="_blank"></asp:HyperLink>
   7:    </ItemTemplate>
   8: </asp:TemplateField>

Here is how to get the same result by using an HyperLinkField and setting the DataNavigateUrlFields and DataNavigateUrlFormatString properties:

   1: <asp:HyperLinkField HeaderText="CustomerID" DataTextField="CustomerId" 
   2:     DataNavigateUrlFields="CustomerId"
   3:     DataNavigateUrlFormatString="~/CustomerInfo.aspx?CustId={0}"  
   4:     Target="_blank" />

The end result is exactly the same but the it is a lot easier to use the HyperLinkField than the TemplateField!



No comments:

Post a Comment