updatepanel中的动态复选框保持选中状态

时间:2015-12-15 23:13:52

标签: c# asp.net checkbox updatepanel dynamic-controls

在使用MasterPage的网站中,我有一个具有UpdatePanel的页面。在其中,有一个ListBox,其中包含用户列表。还有一个动态生成的复选框列表,其中应根据选择的用户检查不同的值。

第一次选择用户时效果很好。但是,当您选择第二个用户时,原始值仍然存在 - 您会看到两个用户的复选框都已选中。

的.aspx

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <h1>Access Database Security Controls</h1>
    <asp:UpdatePanel ID="SecurityControls" runat="server">
        <ContentTemplate>
            <asp:ListBox ID="AccessUsers" runat="server" Rows="15" SelectionMode="Single" OnSelectedIndexChanged="AccessUsers_SelectedIndexChanged" AutoPostBack="true"></asp:ListBox>

            <asp:PlaceHolder ID="SecurityRoles" runat="server"></asp:PlaceHolder>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

代码

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadAllRoles();
    }

    protected void LoadAllRoles()
    {
        for (int i = 0; i < 4; i++)
        {
            Label lbl = new Label();
            lbl.ID = "lbl_" + i.ToString();
            lbl.Text = i.ToString() + " lbl text here";
            SecurityRoles.Controls.Add(lbl);

            CheckBox cb = new CheckBox();
            cb.ID = "cb_" + i.ToString();
            SecurityRoles.Controls.Add(cb);

            SecurityRoles.Controls.Add(new LiteralControl("<br />"));
        }
    }

    protected void AccessUsers_SelectedIndexChanged(object sender, EventArgs e)
    {
        Control page = Page.Master.FindControl("MainContent");
        Control up = page.FindControl("SecurityControls");
        Control ph = up.FindControl("SecurityRoles");

        CheckBox cbRole = (CheckBox)ph.FindControl("cb_" + AccessUsers.SelectedValue);
        if (cbRole != null)
            cbRole.Checked = true;
    }

我在创建复选框时尝试cb.Checked = false;,但即使在部分回发上,SecurityRoles占位符控件也会开始为空。

如何清除复选框?

1 个答案:

答案 0 :(得分:1)

您可以在检查之前尝试取消选中所有其他复选框。

foreach (Control c in ph.Controls)
{
    if(c is CheckBox)
    {
          ((CheckBox)c).Checked=false;
    } 
}