0

(note: I'm tagging it winforms yet I think it does apply to WPF as well)

I have a ComboBox and a model class (let's say Person). Person contains multiple public properties (Name, Age, Sex, Adress and so on).

Is there a (standard) way to bind my ComboBox's data source to these properties, so the ComboBox shows "Name", "Age", "Sex" and "Adress" as its list?

Kilazur
  • 3,089
  • 1
  • 22
  • 48

3 Answers3

1

Your form:

public partial class Form1 : Form
{
    BindingList<PropertyInfo> DataSource = new BindingList<PropertyInfo>();

    public Form1()
    {

        InitializeComponent();

        comboBox1.DataSource = new BindingList<PropertyInfo>(typeof(Person).GetProperties());
        // if want to specify only name (not type-name/property-name tuple)
        comboBox.DisplayMember = "Name";
    }
}

Your class:

public class Person
{
    public string Name { get; set; }
    public uint Age { get; set; }
    public bool Sex { get; set; }
    public string Adress { get; set; }
}
al_amanat
  • 615
  • 3
  • 10
0

To get property names, use reflection:

var propertyNames = person
    .GetType() // or typeof(Person)
    .GetProperties()
    .Select(p => p.Name)
    .ToArray();

(since the result will be the same for all Person instances, I'd cache it, e.g. in static variable).

To display properties in combo box, use DataSource (WinForms):

comboBox.DataSource = propertyNames;

or ItemsSource (WPF):

<ComboBox ItemsSource="{Binding PropertyNames}"/>

(assuming, that current data context contains public property PropertyNames).

Dennis
  • 37,026
  • 10
  • 82
  • 150
0

In WPF:

public class Person
{
    public string Name { get; set; }
    public int? Age { get; set; }
    public string Sex { get; set; }
    public string Address { get;set;}

    public override string ToString()
    {
        return string.Format("{0}, {1}, {2}, {3}", Name, Age, Sex, Address);
    }
}

public class PersonViewModel
{
    public PersonViewModel()
    {
        PersonList = (from p in DataContext.Person
                      select new Person
                      {
                          Name = p.Name,
                          Age = p.Age,
                          Sex = p.Sex,
                          Address = p.Address
                      }).ToList();
    }

    public List<Person> PersonList { get; set; }
    public Person SelectedPerson { get; set; }
}

XAML:

<ComboBox ItemsSource="{Binding PersonList}" SelectedItem="{Binding SelectedPerson}"/>
KostasT
  • 88
  • 3