Bind Generic List to ASP.NET DropDownList Example

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.

This entry was posted in ASP.NET and tagged , . Bookmark the permalink.

One Response to Bind Generic List to ASP.NET DropDownList Example

  1. Peter Bardenhagen says:

    This is great, helped me out a lot! Thanks. :)