5

About 3 hours I am trying to solve this issue. My combo box display to me name of object instead a value for example: A

enter image description here

This is my class:

namespace Supermarket
{
    public class WhareHouseTable
    {
        public string name { get; set; }
        public double cost { get; set; }
        public string offer { get; set; }
    }
}

And here is my code:

private void Form1_Load(object sender, EventArgs e)
{
    List<WhareHouseTable> product = new List<WhareHouseTable>();
    product.Add(new WhareHouseTable { name = "A", cost = 0.63, offer = "Buy 2 for the price of 1" });
    product.Add(new WhareHouseTable { name = "B", cost = 0.20 });
    product.Add(new WhareHouseTable { name = "C", cost = 0.74, offer = "Buy 2; get B half price" });
    product.Add(new WhareHouseTable { name = "D", cost = 0.11 });
    product.Add(new WhareHouseTable { name = "E", cost = 0.50, offer = "Buy 3 for the price of 2" });
    product.Add(new WhareHouseTable { name = "F", cost = 0.40 });

    comboBox2.DataSource = product;
    comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;

    source.DataSource = product;

    foreach (var selected in product)
    {
        comboBox2.Text = selected.name;
        itemCostLabel.Text = selected.cost.ToString();
        offerLabel.Text = selected.offer;
    }
}

In foreach I am trying to get all products and represent them in comboBox and in labels.

What can I do in this situation?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
BinaryTie
  • 281
  • 1
  • 21
  • 49
  • check this ilnk http://stackoverflow.com/questions/600869/how-to-bind-a-list-to-a-combobox-winforms – rashfmnb Apr 01 '16 at 13:15

2 Answers2

9

You need to specify one of the properties in the bound source as its DisplayMember which is going to be displayed and the same or another property as its ValueMember which you can access through selectedItem.Value

comboBox2.DisplayMember = "Name";
comboBox2.ValueMember = "Name";
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
1

You should override toString() method of the class like this:

public override String toString(){
    return name;
}
Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
Waow
  • 21
  • 1