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
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";
}
}
}
In situations like that I typically convert the bound field to a templated field.
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:HyperLink ID="TitleHyperLink" runat="server" ></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
And do the rest of the work in the codebehind.
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var link = (HyperLink)e.Row.FindControl("TitleHyperLink");
if (link != null)
{
if (condition)
{
link.Text = "login";
link.NavigateUrl = "login.aspx";
}
else
{
link.Text = "default text";
link.NavigateUrl = "default.aspx";
}
}
}
}
Instead of creating a new link at this point, grab the link that's already generated as part of the field.
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim link = e.Row.Cells(3).Controls(0)
link.Text = "login"
link.NavigateUrl = "login.aspx"
End If
EDIT: Added If block to avoid action outside item rows.
You could do this in your aspx file :
<asp:HyperLink Text='<%# condition ? "TextIfTrue" : "TextIfFalse" %>' NavigateUrl='<%# condition ? "UrlIfTrue" : "UrlIfFalse" %>' />
or cast your
e.Row.Cells(3).Controls(0)
into a hyperlink and change its values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With