【问题标题】:How can I check the status of a checkbox inside a gridview?如何检查网格视图中复选框的状态?
【发布时间】:2011-03-06 22:23:33
【问题描述】:

我有一个gridview,我制作了一个模板列,里面有一个复选框。 然后我想检查复选框的值。 当未选中该行的复选框时,我正在尝试将该行的可见属性设置为false。 不管我做什么,我总是收到null

肯定是FindControl()有问题,不过我觉得很正常:

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DbInteract dbi = new DbInteract("CONNECTION STRING");
        GridView1.DataSource = dbi.SqlDA("select * from table");
        GridView1.DataBind();
    }
    protected void ProsseguirBtn_Click(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("chk");
                if (!cb.Checked)
                {
                    GridView1.Rows[row.RowIndex].Visible = false;
                }
            }
        }
    }
}

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField>
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="chk" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="nome" HeaderText="jhf" />
            </Columns>
        </asp:GridView>
        <asp:Button ID="ProsseguirBtn" runat="server" Text="Button" 
            onclick="ProsseguirBtn_Click" />

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    </div>
    </form>
</body>
</html>

【问题讨论】:

    标签: c# asp.net gridview checkbox


    【解决方案1】:

    FindControl 不是递归的。换句话说,当您在行上调用 FindControl 时,它只会查看该行包含的直接控件。

    GridViewRow 不直接包含您的控件 - 它包含表格单元格,然后包含您的控件。所以 FindControl 不会找到你的复选框。

    如果您不知道所需的列,则需要使用另一种方法,例如在表格单元格上使用 foreach 循环,或者编写 FindControl 的递归版本。您可以在我的old answer here 中找到我有时使用的版本。

    【讨论】:

      【解决方案2】:

      为什么需要检查!IsPostBack

      我试过这个代码没有这个!IsPostBack检查并且正确找到了CheckBox,否则IsPostBack是假的并且找不到CheckBox的代码将不会被命中。

      【讨论】:

        猜你喜欢
        • 2013-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-25
        • 2012-03-04
        • 2017-03-01
        • 2011-08-06
        相关资源
        最近更新 更多