2011-06-13 32 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

相关问题