【发布时间】:2016-02-20 09:25:45
【问题描述】:
我有一个复选框列表,它从 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;
}
}
}
平均售价:
<anthem:CheckBoxList ID="CheckOpenTimesheets" OnSelectedIndexChanged="select_DeselectAll" runat="server" AutoPostBack="true" >
<asp:ListItem Text="Select/Deselect All" />
</anthem:CheckBoxList>
Edit: The problem seems to be the OnSelectedIndexChanged event firing when the checkboxes other than the select all one is selected.
Edit2:使全选复选框与复选框列表分开。但是,当尝试实现一个功能时,如果在选中全选复选框时未选中一个复选框,则全选复选框将被取消选中,但所有其他复选框都不会“取消选择”。但是这并没有发生,因为全选复选框事件触发了。
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;
}
}
}
【问题讨论】:
-
什么不起作用?添加选择/取消选择所有项目?还是实际执行其他项目的选择和取消选择?
-
更新了我尝试选择/取消选择的代码。我在 asp 代码中添加了选择/取消选择项。
-
这可能是事件的顺序。您可能正在检查/取消选中所有内容,然后重新构建列表。无论如何,您可能需要考虑在客户端使用 JavaScript/Jquery 执行此操作。它会更加用户友好和更快。
-
有没有办法让 onselectedIndexChanged 事件只适用于第一个复选框,也就是全选?这似乎是问题所在。
标签: c# asp.net checkbox checkboxlist