2011-06-13 31 views

回答

0

我寫了這個方法,它的工作原理,但不是最好的性能:

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) 
0

我不知道通過的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控件。

+0

我問使用的Request.Form不是這個。原因是在Page_Init上,這是我可以找出選中的複選框項目的唯一方法。 – 2011-06-13 11:19:48

+0

爲什麼不能直接從'Page_Init'事件處理程序訪問控件? – 2011-06-13 12:42:55

+0

就像我說的那樣,選中的值在Page_LoadViewState事件之後呈現,所以它不存在於Page_Init中,除非您使用Request.Form。 – 2011-06-15 11:29:45

相關問題