Friday 10 May 2013

Maintain the check marks in checkboxlists using session

To specify items that you want to appear in the CheckBoxList control, place a ListItem element for each entry between the opening and closing tags of the CheckBoxList control.

The CheckBoxList control also supports data binding. To bind the control to a data source, first create a data source, such as one of the DataSourceControl objects, that contains the items to display in the control. Next, use the DataBind method to bind the data source to the CheckBoxList control. Use the DataTextField and DataValueField properties to specify which field in the data source to bind to the Text and Value properties of each list item in the control, respectively. The CheckBoxList control will now display the information from the data source.


<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Text="Item 1" Value="1"></asp:ListItem>
    <asp:ListItem Text="Item 2" Value="2"></asp:ListItem>
    <asp:ListItem Text="Item 3" Value="3"></asp:ListItem>
</asp:CheckBoxList>


To determine the selected items in the CheckBoxList control, iterate through the Items collection and test the Selected property of each item in the collection.


int count = CheckBoxList1.Items.Count;
ArrayList values = new ArrayList();

 for (int i = 0; i < count; i++)
 {
               if (CheckBoxList1.Items[i].Selected)
                {
                    values.Add(CheckBoxList1.Items[i].Value);
                }
  }

//save selected checkboxes in session state
Session["CheckBoxList"] = values;



//casting the value from the Session
ArrayList values = (ArrayList)Session["CheckBoxList"];

foreach (ListItem li in CheckBoxList1.Items)
{
                if (values.Contains(li.Value))
                    li.Selected = true;
                else
                    li.Selected = false;
}
   

No comments:

Post a Comment