如何使用Request.Form从CheckBoxList中选择哪些值项目?如何知道使用Request.Form从CheckBoxList中选择哪些值的项目?
我看到这些2形式的键:
[12]: "ctl00$MainContent$cblTimeOfDay$0"
[13]: "ctl00$MainContent$cblTimeOfDay$3"
0和3是由具有4个项目我的复选框列表中选择的值。
我需要找到programmaticlaly上Page_Init这些值
感谢,
如何使用Request.Form从CheckBoxList中选择哪些值项目?如何知道使用Request.Form从CheckBoxList中选择哪些值的项目?
我看到这些2形式的键:
[12]: "ctl00$MainContent$cblTimeOfDay$0"
[13]: "ctl00$MainContent$cblTimeOfDay$3"
0和3是由具有4个项目我的复选框列表中选择的值。
我需要找到programmaticlaly上Page_Init这些值
感谢,
我写了这个方法,它的工作原理,但不是最好的性能:
public static TimeOfDay Create(NameValueCollection httpRequestForm, string checkBoxId)
{
var result = new TimeOfDay();
var selectedCheckBoxItems = from key in httpRequestForm.AllKeys
where key.Contains(checkBoxId)
select httpRequestForm.Get(key);
if (selectedCheckBoxItems.Count() == 0)
{
result.ShowFull = true;
return result;
}
foreach (var item in selectedCheckBoxItems)
{
var selectedValue = int.Parse(item.Substring(item.Length));
switch (selectedValue)
{
case 0:
result.ShowAm = true;
break;
case 1:
result.ShowPm = true;
break;
case 2:
result.ShowEvening = true;
break;
case 3:
result.ShowFull = true;
break;
default:
throw new ApplicationException("value is not supported int the check box list.");
}
}
return result;
}
,并使用它像这样:
TimeOfDay.Create(this.Request.Form, this.cblTimeOfDay.ID)
我不知道通过的Request.Form访问这些。你不能访问强类型的CheckBoxList
控件本身吗? This article提供了一种简单的方法,接受CheckBoxList
并返回所有选定的值;您可以更新此为参考返回所选的项目,或任何其他具体要求如下:
public string[] CheckboxListSelections(System.Web.UI.WebControls.CheckBoxList list)
{
ArrayList values = new ArrayList();
for(int counter = 0; counter < list.Items.Count; counter++)
{
if(list.Items[counter].Selected)
{
values.Add(list.Items[counter].Value);
}
}
return (String[]) values.ToArray(typeof(string));
}
所以,你Page_Init
事件处理程序中,调用像这样:
var selectedValues = CheckboxListSelections(myCheckBoxList);
凡myCheckBoxList
是参考您的CheckBoxList
控件。
我问使用的Request.Form不是这个。原因是在Page_Init上,这是我可以找出选中的复选框项目的唯一方法。 – 2011-06-13 11:19:48
为什么不能直接从'Page_Init'事件处理程序访问控件? – 2011-06-13 12:42:55
就像我说的那样,选中的值在Page_LoadViewState事件之后呈现,所以它不存在于Page_Init中,除非您使用Request.Form。 – 2011-06-15 11:29:45