updatepanel中动态复选框保持选中状态
问题描述:
在使用MasterPage的站点中,我有一个包含UpdatePanel的页面。里面有一个列表框,其中包含用户列表。还有一个动态生成的复选框列表,应根据选择哪个用户检查不同的值。updatepanel中动态复选框保持选中状态
第一次选择用户时效果很好。但是,当您选择第二个用户时,原始值将保留 - 您会看到选中的两个用户的复选框。
的.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;
当我创建了checkboxs,但即使在部分回发时,SecurityRoles占位符控件开始空虚。
如何获取复选框以清除?
答
您可以尝试取消选中所有其他复选框,然后再选中一个复选框。
foreach (Control c in ph.Controls)
{
if(c is CheckBox)
{
((CheckBox)c).Checked=false;
}
}
是的,这确实解决了这个问题。但是,我觉得我正在让系统做很多额外的工作。在每次部分回发时,它都必须查询数据库(我在示例代码中放置for循环的位置)以重新构建复选框列表,现在我循环遍历所有数据库以确保它们清晰。有没有更好的方法来做这个接口? – wham12
如果你这样做,我没有看到你要去哪里数据库,你总是可以使用ViewState –