mardi 15 décembre 2015

Dynamic checkboxes in updatepanel staying checked

Within a site using a MasterPage, I have a page which has an UpdatePanel. Inside that, there is a ListBox which contains a list of users. There is also a dynamically generated list of checkboxes, which should have different values checked based upon which user is selected.

It works great the first time you select a user. However, when you select a second user, the original values remain - you see the checkboxes of both users checked.

.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>

code behind

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

I've tried doing cb.Checked = false; when I am creating the checkboxs, but even on the partial postbacks, the SecurityRoles placeholder control starts out empty.

How do I get the checkboxes to clear?




Aucun commentaire:

Enregistrer un commentaire