Adding ListItems using code. Since all the list controls inherit from ListControl class, AddListItems() method can be used to add listitems to any list control. A parent class reference variable can point to a derived class object.

This fact allows us to pass any list control into the AddListItems() method as a parameter. We have discussed about inheritance in Part 21 and polymorphism in Part 23 of C# Video Tutorial Series.protected void Page_Load(object sender, EventArgs e){if (!IsPostBack) { AddListItems(DropDownList1); AddListItems(CheckBoxList1); AddListItems(RadioButtonList1); AddListItems(ListBox1); AddListItems(BulletedList1); }}private void AddListItems(ListControl listControl){ ListItem li1 = new ListItem("Item1", "1"); ListItem li2 = new ListItem("Item2", "2"); ListItem li3 = new ListItem("Item3", "3");

ListBox (If SelectionMode=Single), RadioButtonList and DropDownList allows user to select only one item. So, use SelectedIndex and SelectedItem properties to retrieve the Text, Value and Index of the selected listitem.

Reusable method that can be used with any control that derives from ListControl class, but works best with controls that allows single selection.private void RetrieveSelectedItemTextValueandIndex(ListControl listControl){if (listControl.SelectedIndex != -1) { Response.Write("Text = " + listControl.SelectedItem.Text + "<br/>"); Response.Write("Value = " + listControl.SelectedItem.Value + "<br/>"); Response.Write("Index = " + listControl.SelectedIndex.ToString()); }}