Let us suppose you had a simple class of
tags that you wanted to bind to an ASP.NET DropDownList control.
public class TagDetails
{
private int tagID;
public int TagID
{
get { return tagID; }
}
private string tagName;
public string TagName
{
get { return tagName; }
set { tagName = value; }
}
public TagDetails(int tagID, string tagName)
{
this.tagID = tagID;
this.tagName = tagName;
}
}
The DropDownList control on the .ASPX page looked like this.
<asp:DropDownList ID="ddlTagList" runat="server"/>
And for this class you had a method to return all tags called
GetTags. How would you bind it to an ASP.NET DropDownList control? As such.
List<TagDetails> tags = new List<TagDetails>();
tags = tagDB.GetTags();
ddlTagList.DataSource = tags;
ddlTagList.DataTextField = "TagName";
ddlTagList.DataValueField = "TagID";
ddlTagList.DataBind();
At this point you may wish to add a blank item or
select item row at the top of the DropDownList. That code can be found at
Add Item to DropDownList After DataBind.
Labels: ASP.NET, DropDownList, Generic-List