smk081
smk081

Reputation: 1145

Binding the value of an object's property to a data bound ComboBox in .NET WinForms

Currently building a WinForms data collection tool using C# and have been able to implement the binding of the values of my underling object/entity's properties to controls on the my form, e.g. TextBoxes, MaskedTextBoxes and Checkboxes to properties on my domain model class (e.g. Person class). However, I have not been able to do this binding successfully with the ComboBox control.

With my Person class looking basically like this:

public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int? Gender { get; set; }
    }

I am using the ComboBox's DataSource property to bind to a Dictionary and setting the ValueMember and DisplayMember accordingly. Doing so successfully populates that ComboBox with my reference data (display value and coded value) at run-time.

Dictionary<int, string> genderValues = repository.GetGenderValues()
cboGender.DataSource = new BindingSource(genderValues, null);
cboGender.ValueMember = "Key";
cboGender.DisplayMember = "Value";

However, when I try to bind my Person object's property 'Gender' to this ComboBox, following the pattern that worked with other control types (TextBox, CheckBox, etc.)

cboGender.DataBindings.Add(new Binding("ValueMember", _currentPerson, "Gender"));

The value of Gender on my person object is always NULL even after selecting an item in the Gender ComboBox. Perhaps I am overlooking an additional step needed for binding the ValueMember of a ComboBox to a object property?

Upvotes: 0

Views: 575

Answers (2)

Ricardo Rodrigues
Ricardo Rodrigues

Reputation: 482

Maybe this will help:

cboGender.DataBindings.Add("SelectedIndex", genderValues, "Value", false, DataSourceUpdateMode.OnPropertyChanged);

Upvotes: 0

Crowcoder
Crowcoder

Reputation: 11514

ValueMember is a string and it does not change with a different selection in the combobox. You need to use one of the Selected... properties. Since it's an int, use SelectedValue.

Upvotes: 0

Related Questions