We help IT Professionals succeed at work.

ASP.NET C#: Dynamic text in GridView HyperLinkField

poultarp asked
Hello All

I have a GridView on an ASP.NET C# website that contains data from a database. In the GridView I have a HyperLinkField.

What I want to do is change the text of the HyperLinkField depending on the value of one of the GridView Columns (if the column is 0 the HyperLinkField text should be "Activate" and if the value is 1 the text should be "Block").

Does anyone know how this can be done?

Søren Augustesen
Watch Question

What you will need to do is convert your hyperlinkfield to a templatefield (containing a HyperLink) and handle the onRowDataBound event of the grid, an

so your markup would contain something like:

    <asp:HyperLink ID="HyperLinkBlockActivate" runat="server" NavigateUrl='<%# Eval("ID", "~/DoSomething.aspx?ID={0}") %>' />

and your code for the eventhandler would be:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  if (e.Row.RowType == DataControlRowType.DataRow)
     //Get the data row that is the source for this row
      DataRowView drv = ((DataRowView)e.Row.DataItem);

   //Get a reference to the hyperlink
   HyperLink HyperLinkBlockActivate = e.Row.FindControl("HyperLinkBlockActivate")

    //Check your trigger value and set the text
    if ((bool)drv["BitField"])
        HyperLinkBlockActivate.Text = "Block";
        HyperLinkBlockActivate.Text = "Activate";

There's also some good explanations and examples at http://www.simple-talk.com/dotnet/asp.net/take-row-level-control-of-your-gridview/ 

Let me know if you do have any issues

Mark (@delradie)


you can use this

Text='<%# Eval("colname")%> == "1" ? "Yes" : "No"

this is just example


Hello Mark

Thank you for your answer.

I have one quick question:

In the <%Eval %> line, how do I pass more than one value to the URL parameters?

Søren Augustesen
You could modify the NavigateUrl property in the rowdatabound as well as the text, or you could go for something like the following in the markup:

NavigateUrl= '<%# String.Format"~/DoSomething.aspx?ID1={0}&ID2={1}", HttpUtility.UrlEncode(Eval("ID")), HttpUtility.UrlEncode(Eval("SomethingElse"))) %>'


Thank you Mark - it works just as I want it to!

Søren Augsutesen
Glad to help. It's a very useful technique, and one I use almost daily.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.