我有一个复选框列表,它从SQL表中获取其项目,并根据从下拉菜单中选择的内容进行更改。我试图在该列表中添加另一个复选框,该复选框充当全选/取消全选框。我在这个站点上看到了一些示例,但似乎没有什么正常工作。
预期功能:
当选中此框时,所有其他框都被选中。
当取消选中此框时,所有其他框都被取消选中。
当选中此框时,如果另一个框然后被取消选中,则取消全选框也会被取消选中。
C#:
List<ListItem> toBeRemoved = new List<ListItem>();
//removes items when new item from dropdown is selected
for (int i = 1; i < CheckOpenTimesheets.Items.Count; i++)
{
toBeRemoved.Add(CheckOpenTimesheets.Items[i]);
}
for (int i = 0; i < toBeRemoved.Count; i++)
{
CheckOpenTimesheets.Items.Remove(toBeRemoved[i]);
}
lblOpenTimesheets.Text = "";
String sql = "sql statement here";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("userid", ddlActingAs.SelectedValue.ToString()));
SqlDataReader reader = command.ExecuteReader();
//Adds items to the checkboxlist
while (reader.Read())
{
ListItem item = new ListItem();
item.Text += reader.GetDateTime(0).ToString("MM/dd/yyyy") + " is open";
item.Value = reader["StartDate"].ToString();
CheckOpenTimesheets.Items.Add(item);
}
CheckOpenTimesheets.UpdateAfterCallBack = true;
reader.Close();
我尝试进行选择/取消选择的方法:
protected void select_DeselectAll(object sender, System.EventArgs e)
{
if (CheckOpenTimesheets.Items[0].Selected == true)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = true;
}
}
else
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = false;
}
}
}
ASP:
<anthem:CheckBoxList ID="CheckOpenTimesheets" OnSelectedIndexChanged="select_DeselectAll" runat="server" AutoPostBack="true" >
<asp:ListItem Text="Select/Deselect All" />
</anthem:CheckBoxList>
编辑:问题似乎是当选择“全选”以外的复选框时,OnSelectedIndexChanged事件会触发。
编辑2:将“全选”复选框与复选框列表分开。但是,当试图实现这样一个功能,即如果在选中了“全选”复选框的情况下取消选择某个复选框,则“全选”复选框将被取消选择,但所有其他复选框不会“取消选择”。然而,这并没有发生,因为“全选”复选框的事件已经触发了。
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = chkAll.Checked;
}
}
protected void checkbox_Selected(object sender, EventArgs e)
{
chkAll.CheckedChanged -= chkAll_CheckedChanged;
foreach (ListItem item in CheckOpenTimesheets.Items)
{
if ((item.Selected = false) && (chkAll.Checked = true))
{
chkAll.Checked = false;
}
}
}