Ask the Expert

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";
  cbProducts.DataBind();
 }
}

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)
{
 Response.Write(cbProducts.SelectedValue);

This was first published in July 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: