当BoundField为零时禁用ButtonField

时间:2016-11-02 16:33:32

标签: c# sql-server gridview webforms

我有GridView填充Page_Load

protected void Page_Load(object sender, EventArgs e) {
  if (!Page.IsPostBack) {
    GridView1.DataSource = actBO.BuscarActividades();
    GridView1.DataBind();
  }
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
            <asp:BoundField DataField="Class" HeaderText="Class" /> 
            <asp:BoundField DataField="Day" HeaderText="Day" />
            <asp:BoundField DataField="Time" HeaderText="Time" />
            <asp:BoundField DataField="Vacants" HeaderText="Vacants" />          

            <asp:ButtonField ButtonType="Button" HeaderText="Book" Text="Book"/>

        </Columns>
 </asp:GridView>

“Vacants”栏显示int(表示班级中空置预订空间的数量)。

每一行都有一个按钮来预订特定的课程。当“Vacants”字段为零时,我需要设置一个条件,因此“Book”按钮将被禁用。

到目前为止,这就是它的样子:image

如您所见,我需要在没有空位时禁用该按钮。它不应该被点击。

1 个答案:

答案 0 :(得分:0)

为此,您必须注册OnRowDataBound事件。更多解释可以在here中找到。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
            <asp:BoundField DataField="Class" HeaderText="Class" /> 
            <asp:BoundField DataField="Day" HeaderText="Day" />
            <asp:BoundField DataField="Time" HeaderText="Time" />
            <asp:BoundField DataField="Vacants" HeaderText="Vacants" />          
            <asp:ButtonField ButtonType="Button" HeaderText="Book" Text="Book"/>
        </Columns>
 </asp:GridView>


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // get your button via the column index; ideally you could use template field and put your own button inside
        var button = e.Row.Cell[5].Controls[0] as Button;
        int vacant = 0;
        var vacantVal = int.TryParse(e.Row.Cell[4].Text, out vacant);
        if (button != null)
        {
            button.Enabled = vacant > 0;
        }
    }
}

希望它有所帮助。