【发布时间】:2014-01-16 14:25:55
【问题描述】:
我有一些工作代码,但我认为这不是实现目标的最佳方式。
我有一个包含 5 个项目的 CheckBoxList - 4 个单独的项目和 1 个“全选”项目。选择完全选择时,我希望其他4要为用户签出。当 Select All 被取消选择时,我希望其他 4 个为用户取消选中。
我在 StackOverflow 和 Google 上发现的一堆东西只是建议遍历 CheckBoxList.Items,但这不适用于我的情况。例如,假设用户未选中 Item #3 - 这将触发 OnSelectedIndexChanged 事件,此时我将开始循环遍历 Items。我会发现未选择“全选”项目,因此我会取消选择所有项目。因此,用户会选中第 3 项,只是为了让他们立即取消选择它。
下面是我的工作代码,但它使用了一些奇怪的功能,我无法想象这是实现我正在寻找的最佳方式。
protected void StatusCheckBoxListChanged(object sender, System.EventArgs e)
{
//Crazy code I found online to determine which item triggered the event
CheckBoxList list = (CheckBoxList)sender;
string[] control = Request.Form.Get("__EVENTTARGET").Split('$');
int index = control.Length - 1;
ListItem li = (ListItem)list.Items[Int32.Parse(control[index])];
if (li.ToString().Equals("Select All")) //If it was the "Select All" Item which triggered the event
{
//If it was checked, check off everything. If it was unchecked, uncheck everything.
for(int i = 0; i < StatusCheckBoxList.Items.Count; i++)
{
StatusCheckBoxList.Items[i].Selected = StatusCheckBoxList.Items.FindByValue("Select All").Selected;
}
}
}
【问题讨论】:
-
你能提供
CheckBoxList的标记吗? -
当然,虽然它是相当标准的。
<asp:CheckBoxList ID="StatusCheckBoxList" OnSelectedIndexChanged="StatusCheckBoxListChanged" runat="server" AutoPostBack="True"> -
似乎最好使用另一个
CheckBox,而不是使用来自CheckBoxList的项目 -
也许你是对的,我只是更喜欢有几个项目的布局,其中一个选择所有其他项目。无论如何,问题仍然是是否有比我提供的代码更好的方法来获取最近选择的复选框。对我来说,这是最好的选择似乎很奇怪。