Monday, September 27, 2010

Add Items to Populate ASP.Net CheckBoxList Control Dynamically

The ASP.Net CheckBoxList control also provides the method to populate it by adding the list items dynamically using C# code. You can use the Add method of Items collection property of CheckBoxList control to populate the items programmatically. The Items property gets the collection of list items stored in the CheckBoxList control. It belongs to the ListItemCollection class and provides the read-only member of this collection class. The Items property further enables you to access the public methods of ListItemCollection class that allow you to add or remove the list items. Here we will use the Add method to populate the list items into the CheckBoxList control.

Following are the two overloaded ways of using the Add method of Items collection property of CheckBoxList:

1.[CheckBoxList].Items.Add( ListItem item );

It allows you to add the specified list item at the end of CheckBoxList collection. You can use the well suited overloaded way of ListItem class constructor to add a new item.

2.[CheckBoxList].Items.Add( string text );
It appends the collection of list items of CheckBoxList control by adding the specified string at the end of collection.
For adding the ListItem using first overloaded Add method you can use the following overloaded constructor of ListItem class:

new ListItem( string text, string value );
 
It allows you to add the ListItem with its text that will appear in the CheckBoxList control along with its value that will work at the back end.

Example:

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>

C# Code:
There are different ways to add the List Items into the CheckBoxList control. In the following samples we have shown 2 different ways to add the ListItems:
Example 1:
ListItemCollection itemsCollection = CheckBoxList1.Items;
itemsCollection.Add(new ListItem("item 1", "1"));
itemsCollection.Add(new ListItem("item 2", "2"));
itemsCollection.Add(new ListItem("item 3", "3"));
itemsCollection.Add(new ListItem("item 4", "4"));
itemsCollection.Add(new ListItem("item 5", "5"));
Example 2:
CheckBoxList1.Items.Add(new ListItem("item 1", "1"));
CheckBoxList1.Items.Add(new ListItem("item 2", "2"));
CheckBoxList1.Items.Add(new ListItem("item 3", "3"));
CheckBoxList1.Items.Add(new ListItem("item 4", "4"));
CheckBoxList1.Items.Add(new ListItem("item 5", "5"));
You can build your logic to add the ListItems into the ListItemCollection of CheckBoxList control using any of the above C# code. You can also use C# for loop to add the items that will also reduce the code lines.
Output:
Get the output for above discussed code from the following link:
                               
                                Populate CheckBoxList Control Items Dynamically


No comments:

Post a Comment