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.
|