2010-04-20 89 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); 
      } 
     } 
    }