Monday, December 12, 2011

How to get HyperLinkField value in GridView

How can we get HyperLinkField text value from GridView control when the field is data-bound? BoundField data can be retrieved by simply using .Text property. But unlike BoundField, HyperLinkField.Text property does not return the same text value as shown in GridView.
In the following example, GridView has three columns - one for HyperLinkField, 2nd one for BoundField, and the last one for Delete CommandField. Let us say we want to get first column value as a key, when user clicks Delete button in 3rd column.
<asp:GridView ID="grid1" runat="server" onrowdeleting="grid1_RowDeleting">
        <asp:HyperLinkField DataNavigateUrlFields="Link" 
            DataNavigateUrlFormatString="~\{0}" DataTextField="Link"
            HeaderText="Link ID" Target="_blank" />
        <asp:BoundField DataField="Name" HeaderText="Name">
           <itemstyle Width="200px" />
        <asp:CommandField ShowDeleteButton="True" />

So when user clicks Delete button, OnRowDeleting event handler will be fired.
In the event handler, RowIndex will be passed from a GridViewDeleteEventArgs argument. Thus current GridViewRow can be retrieved from Rows[e.RowIndex].

protected void grid1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    GridViewRow row = grid1.Rows[e.RowIndex];
    // Gets HyperlinkField data
    string linkID = ((HyperLink)row.Cells[0].Controls[0]).Text;    
    // Gets BoundField data 
    string name = row.Cells[1].Text;    


Since we want to check first column, row.Cells[0] returns first column of the row as a TableCell object. First child control in the TableCell object is a HyperLink object, so we cast it as HyperLink and gets the Text property of the HyperLink object.