如何使用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