Topic: Binding A Generic List to a DropDownList
Description: This topic will show you how to bind a Generic List to a dropdownlist
First you must have a class that you will use in your Generic List. Below is an example
[Serializable]
public class TopicArea
{
// Private Properties private int _TopicAreaID = 0;
private string _Description = string.Empty;
private bool _AdminOnly = false;
// Constructors
public TopicArea
{ }
public TopicArea(int TopicAreaID, string Description, bool AdminOnly)
{
_TopicAreaID = TopicAreaID;
_Description = Description;
_AdminOnly = AdminOnly;
}
// Public Properties
public int TopicAreaID
{
get { return _TopicAreaID; }
set { _TopicAreaID = (int)value; }
}
public string Description
{
get { return _Description; }
set { _Description = value; }
}
public bool AdminOnly
{
get { return _AdminOnly; }
set { _AdminOnly = (bool)value; }
}
We're going to assume you know how to populate a Generic List, so we'll skip that for that is not the topic at hand.
Next we'll use the Generic List to Bind to a dropdownlist. It can go somewhere in the Page_Load event of your page.
if (!IsPostBack)
{
TopicAreaBLL topicAreaBLL = new TopicAreaBLL();
List<TopicArea> topicArea = topicAreaBLL.GetAll();
ddlTopicArea.DataSource = topicArea;
ddlTopicArea.DataTextField = "Description";
ddlTopicArea.DataValueField = "TopicAreaID";
ddlTopicArea.DataBind();
}