Conditionally hide CommandField or ButtonField in Gridview
asp.net, gridview
Solution
First, convert your `ButtonField` or `CommandField` to a `TemplateField`, then bind the `Visible` property of the button to a method that implements the business logic:
<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Reject"
Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>'
CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then, in the code behind, add in the method:
protected Boolean IsOverAgeLimit(Decimal Age) {
return Age > 35M;
}
The advantage here is you can test the `IsOverAgeLimit` method fairly easily.
Problem
I have a `GridView` displaying person records. I want to conditionally show a `CommandField` or `ButtonField` based on some property of the underlying record. The idea is to only allow a command to be performed on specific people. What is the best way to do this? I'd prefer a declarative solution to a procedural one.