有条件地隐藏 Gridview 中的 CommandField 或 ButtonField [英] Conditionally hide CommandField or ButtonField in Gridview

查看:26
本文介绍了有条件地隐藏 Gridview 中的 CommandField 或 ButtonField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 GridView 显示人员记录.我想根据基础记录的某些属性有条件地显示 CommandFieldButtonField .这个想法是只允许对特定的人执行命令.

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.

推荐答案

首先,将您的 ButtonFieldCommandField 转换为 TemplateField,然后将按钮的 Visible 属性绑定到实现业务逻辑的方法:

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;
}

这里的优点是您可以相当轻松地测试 IsOverAgeLimit 方法.

The advantage here is you can test the IsOverAgeLimit method fairly easily.

这篇关于有条件地隐藏 Gridview 中的 CommandField 或 ButtonField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆