Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do bind list of custom objects to ComboBox?

Tags:

c#

winforms

How do I bind a list of custom objects to a combobox? This is what I have currently:

            this.classCmbo.DataSource = _viewModel.Coarses;
            this.classCmbo.DisplayMember = "Name";
            this.classCmbo.ValueMember = "Id";

I what "Name" to be displayed but I want the "Id" to be the value associated with a selection. How do you do this in winforms?

Here is the Coarse obj:

 public class Coarse
    {
        public virtual int Id { get; private set; }
        public virtual string Name { get;  set; }
    }

Thanks...

like image 305
Nick Avatar asked Nov 05 '11 23:11

Nick


1 Answers

you can try like this.....

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }
    public Country(string _name)
    {
        Cities = new List<City>();
        Name = _name;
    }
}

List<Country> countries = new List<Country> { new Country("UK"), 
                                     new Country("Australia"), 
                                     new Country("France") };

bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

I hope it will helps you...

like image 65
Glory Raj Avatar answered Nov 14 '22 22:11

Glory Raj