How To 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";

Post a Comment


Close Menu