Posted by: codeproject | October 13, 2007

GridView- Difference between asp:hyperlinkfield and asp:hyperlink

<asp:gridview id=”titlesGrid” runat=”server”
      datasourceid=”titles”
      width=90% cellpadding=5 font-size=”8pt”
      autogeneratecolumns=false
      headerstyle-backcolor=”maroon”
      headerstyle-forecolor=”khaki”
      headerstyle-font-bold
      rowstyle-verticalalign=”top”>

      <columns>
         <asp:hyperlinkfieldheadertext=”Title”
            datatextfield=”title”
            datanavigateurlformatstring=”page_details.aspx?id={0}”
            datanavigateurlfields=”id” />

          <asp:boundfield headertext=”ID”
            datafield=”id” />

         <asp:boundfield headertext=”Name”
            datafield=”Name” />

         <asp:boundfield headertext=”Fee”
            datafield=”fee”
            htmlencode=false
            dataformatstring=”{0:n2}”
            itemstyle-horizontalalign=”right” />

      </columns>

   </asp:gridview>

The only drawback I found in a asp:hyperlinkfieldthat you cannot bound the field or concatenate the string like below expression. You will get an error. 

<asp:hyperlinkfieldheadertext=”Title”
            datatextfield=”title”
            datanavigateurlformatstring=”page_details.aspx?id={0}
&status=<%= Status %>“  datanavigateurlfields=”id” />

Below is a suggested way to get it done.
Create an template column and add a hyperlink to it.

<asp:TemplateField HeaderText=”Link”>
<ItemTemplate>
<asp:HyperLink ID=”hltitle” runat=”server” NavigateUrl=’<%# FormatUrl( (int) Eval(“title”) ) %>’ Text = ‘<%# Eval(“title”) %>‘ />

</ItemTemplate>
</asp:TemplateField>

Most recommendable way to do it, do it through code behind. use RowDataBound events.

Sub GridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

If
e.Row.RowType = DataControlRowType.DataRow Then
‘You can bound your data here 
End If

I would appreciate your comments.
Rana
 


Responses

  1. My code is worked by using this code
    Thanks

  2. Thanks for this! :)


Leave a response

Your response:

Categories