jhony3 jhony3 - 1 year ago 62
C# Question

What is the equivalent of SelectedValuePath and SelectedValue in Winforms ComboBox?

Does someone know what is the equivalent of

from WPF comboboxes to WinForms? I tried with
but that doesn't work...

Answer Source

In WPF, SelectedValuePath gets or sets the path that is used to get the SelectedValue from the SelectedItem. It's exactly what ValueMember serves in Windows Forms, it gets or sets the path of the property to use as the actual value for the items of ComboBox.

In windows forms when you want to use data-binding with a ComboBox, you should use this properties:

  • DataSource
    An object that implements the IList interface or an Array.
  • DisplayMember
    The name of an object property that is contained in the collection specified by the DataSource property. If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead.
  • ValueMember
    epresenting a single property name of the DataSource property value, or a hierarchy of period-delimited property names that resolves to a property name of the final data-bound object.

  • SelectedValue
    An object containing the value of the member of the data source specified by the ValueMember property.


Put a ComboBox and a Button on your form and handle Load event of Form and Click event of Button like below below. By click on Button you will see the selected item of ComboBox will be changed to Two. Don't forget to register event handlers for events.

public class Category
    public int Id { get; set; }
    public string Name { get; set; }

private void Form1_Load(object sender, EventArgs e)
    var categories = new List<Category>()
        new Category(){Id=1, Name= "One"},
        new Category(){Id=2, Name= "Two"},
        new Category(){Id=3, Name= "Three"},

    this.comboBox1.DataSource = categories;
    this.comboBox1.DisplayMember = "Name";
    this.comboBox1.ValueMember = "Id";

private void button1_Click(object sender, EventArgs e)
    this.comboBox1.SelectedValue = 2;