我的网页上有一个CheckBox和一个CheckBox列表。
如果选择了CheckBox,则应该选择CheckBoxList中的所有CheckBoxes,如果CheckBox未选中,类似地,CheckBox中的所有CheckBoxes都应该被取消选中(未选中)。
.aspx代码
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Item A</asp:ListItem>
<asp:ListItem>Item B</asp:ListItem>
<asp:ListItem>Item C</asp:ListItem>
<asp:ListItem Selected="True">Item D</asp:ListItem>
<asp:ListItem>Item E</asp:ListItem>
<asp:ListItem>Item F</asp:ListItem>
<asp:ListItem>Item G</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="allChkBox" Text="Select all" runat="server"
oncheckedchanged="allChkBox_CheckedChanged" />我试过做这样的事,但不管用:
bool prevSelection = false;
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
if (!prevSelection)
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = true;
}
}
else
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = false;
}
}
prevSelection = !prevSelection;
}发布于 2012-03-06 03:11:32
我更喜欢用客户端脚本来做这样的事情,这样页面就不用做回发了
如果这是可能的,请尝试在单击时触发javascript函数来执行循环并选择.就像这样
<script type="text/javascript">
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
if(aa.elements[i].type == 'checkbox') {
aa.elements[i].checked = checked;
}
}
}
</script>发布于 2012-03-06 03:10:08
我已经有一段时间没有涉足ASP.NET了,但是您的prevSelection字段将在每个请求中初始化为false。该值不会在请求之间持久化。因此,您需要将其存储在视图状态或缓存中,并将其从那里加载到事件处理程序中,或者更好的是,将方法更改为如下所示:
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = allChkBox.Selected;
}
}发布于 2015-07-23 06:48:17
如果我理解了这个要求,对吗?)在默认情况下,这将使selected控件中的所有项呈现如下:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
LoadCountryList();
}
private void LoadCountryList()
{
_ctx = new PayLinxDataContext();
chkCountries.DataSource = _ctx.Countries.OrderBy(c => c.Name);
chkCountries.DataBind();
foreach (ListItem item in chkCountries.Items)
{
item.Selected = true;
}
}
https://stackoverflow.com/questions/9577350
复制相似问题