0
votes

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?

1
What exactly do you want to achieve? - Ndubuisi Jr
Why don't you use a List<Person> as the DataSource of the BindingSource (so you can use it for all the other Controls), setting DisplayMember and ValueMember to the properties you want as the Items' Text and corresponding value? What's the use of a (undefined) Dictionary here? - Jimi

1 Answers

0
votes

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.