In this article, we will create an ArrayList of Item objects and bind it to a DropDownList control using DataSource property in asp.net application. Let us create a class named Item as shown in the article - Binding an ArrayList with GridView control in ASP.Net application.
Next, declare a new ArrayList and start adding elements to it using the Add() method in the Page_Load method. Now, bind the arrayList using DropDownList control's DataSource property as shown in the code below. Set the DataTextField property of the DropDownList control to Code and DataValueField property of the DropDownList control to Name. The DataBind() method of the DropDownList control binds the data source in this case arraylist to the DropDownList control. The code given below demonstates how to bind an arraylist with dropdownlist in asp.net application.
protected void Page_Load(object sender, EventArgs e)
ArrayList list = new ArrayList();
list.Add(new Item("I001", "Item1"));
list.Add(new Item("I002", "Item2"));
list.Add(new Item("I003", "Item3"));
list.Add(new Item("I004", "Item4"));
DropDownList1.DataSource = list;
DropDownList1.DataTextField = "Code";
DropDownList1.DataValueField = "Name";
The below code demonstrates how to bind an ArrayList with combobox control in a windows application.
comboBox1.DataSource = list;
comboBox1.ValueMember = "Code";
comboBox1.DisplayMember = "Name";