How to programmatically replace an HyperLinkField in a ASP.NET GridView

CiccioMiami picture CiccioMiami · Feb 29, 2012 · Viewed 21.2k times · Source

I have an ASP.NET Web Forms application. In my application I have a GridView that works smoothly. I have several text fields and the last one is a <asp:hyperlinkfield>.

Now I would like to programmatically change the field by placing a simple link instead of the hyperlinkfield if a specific condition is fulfilled. Therefore I catch the onRowDataBound event:

Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles myGridView.RowDataBound

    If (condition) Then
           Dim link = New HyperLink()
           link.Text = "login"
           link.NavigateUrl = "login.aspx"
           e.Row.Cells(3).Controls.Add(link)
        End If
    End If
End Sub

where n is the cell where the hyperlinkfield is placed. With this code it just adds to the hyperlinkfield the new link. How can I replace it?

PS: The code is in VB6 but I am a C# programmer, answers with both languages are accepted

Answer

dugas picture dugas · Feb 29, 2012

Remove the control you want to replace from the collection before adding the new one:

protected void TestGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    HyperLink newHyperLink = new HyperLink();
    newHyperLink.Text = "New";
    e.Row.Cells[3].Controls.RemoveAt(0);
    e.Row.Cells[3].Controls.Add(newHyperLink);
  }
}

But I agree with the others, just change the existing link's properties:

protected void TestGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    HyperLink link = e.Row.Cells[0].Controls[0] as HyperLink;
    if (link != null)
    {
      link.Text = "New";
      link.NavigateUrl = "New";
    }
  }
}