The ASP.Net RadioButtonList 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 RadioButtonList control to populate the items programmatically. The Items property gets the collection of list items stored in the RadioButtonList 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 RadioButtonList control.
Following are the two overloaded ways of using the Add method of Items collection property of RadioButtonList:
1. [RadioButtonList].Items.Add( ListItem item );
It allows you to add the specified list item at the end of RadioButtonList collection. You can use the well suited overloaded way of ListItem class constructor to add a new item.
2. [RadioButtonList].Items.Add( string text );
It appends the collection of list items of RadioButtonList 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:
It allows you to add the ListItem with its text that will appear in the RadioButtonList control along with its value that will work at the back end.
Sample Code to Populate RadioButtonList Control Dynamically
HTML Code:
C# Code:
There are different ways to add the List Items into the RadioButtonList control. In the following samples we have shown 2 different ways to add the ListItems:
Example 1:
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:
RadioButtonList2.Items.Add(new ListItem("item 2", "2"));
RadioButtonList2.Items.Add(new ListItem("item 3", "3"));
RadioButtonList2.Items.Add(new ListItem("item 4", "4"));
RadioButtonList2.Items.Add(new ListItem("item 5", "5"));
You can build your logic to add the ListItems into the ListItemCollection of RadioButtonList 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.
0 comments:
Post a Comment