Problem solve Get help with specific problems with your technologies, process and projects.

How do I bind a collection to a dropdown list ?

I have a DropDown Web control in my ASP.NET application showing product listing. I basically have a Visual Basic class that does the retrieval of the information from the database. This class returns a collection of product class (this class only has ID and description).

I am not sure how to properly bind this collection to the dropdown list such that when displaying the information, it shows the description, but when upon submit of the form this dropdown is a part of, I want the product ID to be stored in the database.

I know that somehow DataValueField and DataTextField should be used, but I am not sure what should I assign them to.

Assuming the collection I get back from that VB class is called productCollection, and the attributes of the product class are productId and productDesc, what should I assign the above fields (DataBalueField and DataTextField) to achieve my purpose?

Any ideas would be greatly appreciated.
All you need is assign to the DataValueFied and DataTextField the name of the properties you want for each of them. I made a custom typed collection as an example also. The following code shows the classes:

public class Products : CollectionBase
 public Products()
  base.InnerList.Add(new Product("asdf", "hola"));
  base.InnerList.Add(new Product("wer4wer", "chau"));

 public Product this [int idx]
  get { return base.InnerList[idx] as Product; }
  set { base.InnerList[idx] = value; }

public class Product
 public string ProductId
  get { return _productid; }
  set { _productid = value; }
 } string _productid;

 public string ProductDescription
  get { return _description; }
  set { _description = value; }
 } string _description;
 public Product(string id, string description)
  _productid = id;
  _description = description;

The page code is pretty simple:

private void Page_Load(object sender, System.EventArgs e)
 if (!IsPostBack)
  cbProducts.DataSource = new Products();
  cbProducts.DataTextField = "ProductDescription";
  cbProducts.DataValueField = "ProductId";

If you had a button that causes a postback, you could get the selected product ID as follows:

private void btnProducts_Click(object sender, System.EventArgs e)

Dig Deeper on .NET tutorials, guides and quizzes

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.