2010-04-20 91 views
0

您可以請幫我在會話中存儲複選框列表項。複選框列表的會話狀態

我有一個複選框列表如下

asp:CheckBoxList ID="cblScope" runat="server" 
     onselectedindexchanged="cblScope_SelectedIndexChanged"> 

    asp:ListItem ID="liInScope" runat="server" Value="true">In Scope (Monitored)</asp:ListItem> 
    <asp:ListItem ID="liOutOfScope" runat="server" Value="true">Out of Scope (Unmonitored)</asp:ListItem> 

/asp:CheckBoxList> 

我有複選框的值存儲在會議上他們cheked時。

回答

2

可以將所有物品(是否選中與否)添加到會話這樣的:

Session.Add("AllItems", cblScope.Items); 

或者你可以用更多的代碼添加選中的代碼:

List<ListItem> selectItems = new List<ListItem>(); 

foreach (ListItem item in cblScope.Items) 
{ 
    if (item.Selected) 
     selectItems.Add(item); 
} 

Session.Add("MySelectedItems", selectItems); 
2

ID和runat對於ListItems不是合適的標籤。您的複選框列表應該看起來更像這樣

<asp:CheckBoxList ID="cblScope" runat="server" 
     onselectedindexchanged="cblScope_SelectedIndexChanged"> 

    <asp:ListItem Value="In Scope">In Scope (Monitored)</asp:ListItem> 
    <asp:ListItem Value="Out of Scope">Out of Scope (Unmonitored)</asp:ListItem> 

</asp:CheckBoxList> 

請注意,在複選框列表中,可以選擇多個項目。如果您打算將它作爲單個選擇,則應該使用RadioButtonList控件。至於獲取已被選中的項目,你可以迭代它們甚至使用LINQ。以下是將選定值存儲在字符串列表中的示例。

迭代:

List<string> selections = new List<string>(); 
foreach (ListItem listItem in cblScope.Items) 
{ 
    if (listItem.Selected) 
    { 
     selections.Add(listItem.Value);     
    } 
} 

Session["selections"] = selections; 

LINQ:

var selections = (from ListItem listItem in cblScope.Items 
        where listItem.Selected 
        select listItem.Value).ToList(); 

Session["selections"] = selections; 
2

網頁A:

//Add namespace for List 

using System.Collection.Generic; 

protected void BtnNext_Click(object sender, EventArgs e) 
    {     

     List<ListItem> selection = new List<ListItem>(); 
     foreach (ListItem li in CheckBoxList1.Items) 
     { 
      if (li.Selected) 
      { 
       selection.Add(li); 
       //string ch = li.Value; 
      } 
     } 
     Session["emp"] = selection; 
     Response.Redirect("Page2.aspx"); 
     //Server.Transfer("Page2.aspx"); 

    } 

第2頁: -

using System.Collection.Generic; 

protected void Page_Load(object sender, EventArgs e) 
    { 

     if (Session["emp"] != null) 
     { 
      List<ListItem> name=(List<ListItem>)Session["emp"];   

      foreach (ListItem li in name) 
      { 
       Response.Write(li); 
      } 
     } 
    }