Donate

Removing Hyperlink Or 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).
Removing Hyperlink Or LinkButton In A GridViewColumn Based From A Condition Or Value
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>

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.