Digital Colony!

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.

Labels: , ,

 

Add Item to DropDownList After DataBind

We often want the first option in a drop-down list to not default to the first item in the list. Instead we would prefer the option of adding a --Select Item-- at the top of the asp:DropDownList. After the DataBind, execute an Item.Insert.
ddlAuthor.DataTextField = "FullName";
ddlAuthor.DataValueField = "AuthorID";
ddlAuthor.DataSource = authorDB.GetAuthors();
ddlAuthor.DataBind();
ddlAuthor.Items.Insert(0, "-- Select Author --");

Labels: ,

 

Digital Colony Copyright © 1999-2008 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.