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 );
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: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"));
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.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"));
Output:
Get the output for above discussed code from the following link:Populate CheckBoxList Control Items Dynamically
No comments:
Post a Comment