CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Bind Generic List collection to DropDownList Control in ASP.Net
Submitted By Satheesh Babu B
On 12/2/2008 7:21:16 AM
Tags: ASP.Net,CodeDigest  

Bind Generic List<T> collection to DropDownList Control in ASP.Net

Most of the times, we will bind the DropDownist control by taking the value and text from database. When we do this, we will normally fetch it in the front end as a DataTable object or ArrayList or Generic List<T>.

Below code snippet will help to bind a generic list to dropdownlist control.


        List<Categories> _listCat = new List<Categories>();


        Categories _cat = new Categories();
        _cat.CategoryID = "1";
        _cat.Category = "C#";
        _listCat.Add(_cat);


        _cat = new Categories();
        _cat.CategoryID = "2";
        _cat.Category = "ASP.Net";
        _listCat.Add(_cat);


        _cat = new Categories();
        _cat.CategoryID = "1";
        _cat.Category = "VB.Net";
        _listCat.Add(_cat);


        ddlCategory.DataSource = _listCat;
        ddlCategory.DataTextField = "Category";
        ddlCategory.DataValueField = "CategoryID";
        ddlCategory.DataBind();

In the above code snippet, i have created a generic list List<Categories> with some sample values. Similar to binding the DropDownList control to a DataTable, we need to assign the generic list object to DataSource property of DropDownList control. Also, assign the DataTextField and DataValueField to the property of the object(the object  that represent T in List<T>) and call DataBind() method finally to bind the DropDownList control.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..