I created the following class to model a person:
namespace DataBindingTest
{
public enum colorEnum
{
Red,
Green,
Yellow,
Blue,
}
class Person
{
private string _Name;
private int _Age;
private colorEnum _FavoriteColor;
private bool _HasAllergies;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
public colorEnum FavoriteColor
{
get { return _FavoriteColor; }
set { _FavoriteColor = value; }
}
public bool HasAllergies
{
get { return _HasAllergies; }
set { _HasAllergies = value; }
}
}
}
On my main form, I have a combobox that will be bound to an array of Person objects. When I select a person from this combobox, I want to display their age (in a NumericUpDown control), whether they have allergies (as a checkbox) and their favorite color (in another combobox with DropDownStyle set to DropDownList). To accomplish this, I have:
- Added a comboBox (comboBoxPeople), a NumericUpDown control, a checkBox and another comboBox (comboBoxFavoriteColor) to my form.
- Created a new DataSource from my Person class declared above
- Added a BindingSource to my form
- Set the DataSource property of the BindingSource to the DataSource defined in #2.
- Set the DataSource for comboBoxPeople to the BindingSource and the DisplayMember to the Name property of the BindingSource
- I have bound the Age property of the BindingSource to a NumericUpDown control and the HasAllergies property of the BindingSource to a checkBox control
- In my constructor, I have created an array of 3 Person objects, defined all of their properties and then set the DataSource property of the BindingSource to this array
Thus far, everything is working as expected. Now I'd like to display the person's favorite color (i.e., the FavoriteColor property of the BindingSource) in comboBoxFavoriteColor. I've set the DropDownStyle to DropDownList since FavoriteColor is an enum. However, I'm unclear as to how I should bind this comboBox in order for it to 1) contain the FavoriteColor enum values and 2) have the appropriate color set as the SelectedItem when I choose a person from comboBoxPeople. Can anyone give me an idea on this? Thanks very much!