Home Blog .NET Binding DropDownList to a collection of class
Binding DropDownList to a collection of class
.NET
Written by Dicky   
Friday, 03 June 2011 11:02
AddThis Social Bookmark Button

Usually, when you want to create a dropdownlist dynamically, you can either to create a ListItem manually one by one or you can bind it to a various data source. The most common type is to bind it with a string array, then you can also use HashTable. However, here's a way to bind it to a collection of your own defined class.

for (int i = 0; i < customerRetList.Count; i++)
{
    ICustomerRet customerRet = customerRetList.GetAt(i);

    var customer = new Customer
    {
        Name = customerRet.Name.GetValue(),
        ID = customerRet.ListID.GetValue(),
    };

    customers.Add(customer);
}

DropDownList1.DataSource = customers;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();

As you can see from the code above, you have a Customer class that have Name and ID as its property. customers is a List<Customer>() object. If you used to work with DataGrid or GridView control then you might only need to do DataSource and DataBind. However, with dropdown list you need to assign the DataTextField and DataValueField. All you need to do is to assign the customers object as the dropdown data source and then assign the drop down value and text based on the property name that is available in your class. Simple as that!