Tuesday, May 3, 2016

Removing hyperlink(LinkButton) in a GridViewColumn based from a condition or value

There was a question raised from the forum on how to remove a hyperlink control in a GridViewColumn if a given condition is met. In the example below, the hyperlink(LinkButton) is disabled if Units In Stock is zero (0).
A solution is to disable the LinkButton in the RowDataBoundEvent.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
protected void gvUnitSummary_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (Convert.ToInt32(e.Row.Cells[3].Text) == 0)
        {
            LinkButton lnkUnitID = (LinkButton)e.Row.FindControl("lnkProducts");
            lnkUnitID.Enabled = false;
        }
    }
}

Another solution is to change the column from BoundField to TemplateField. The TemplateField contains a LinkButton and a Label control. Set the Visibility property of the controls accordingly such as LinkButton will be shown if Units In Stock is greater than 0. Otherwise, show the Label control instead.
1
2
3
4
5
6
7
8
<asp:TemplateField HeaderText="Product ID">
    <ItemTemplate>
        <asp:LinkButton ID="lnkProducts" runat="server" CausesValidation="False" 
            Text='<%#Eval("ProductID")%>' Visible='<%# Convert.ToInt32(Eval("UnitsInStock").ToString()) > 0 %>' />
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductID")%>' 
            Visible='<%# Convert.ToInt32(Eval("UnitsInStock").ToString()) <= 0 %>' />
    </ItemTemplate>
</asp:TemplateField>

0 comments:

Post a Comment