How To Bind Generic List to ASP.NET DropDownList Example

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();

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم