tags:

views:

364

answers:

2

Hi all, i'm binding a class to a windows form using the object data source: binding simple properties to textboxes works fine, but i need to bind enum properties to comboboxes too, such as:

    public enum MyEnum
    {
        Val1,
        Val2,
        Val3
    }
    private MyEnum enumVal;

    public MyEnum EnumVal
    {
        get { return enumVal; }
        set { enumVal = value; }
    }

How to accomplish this using a binding source? I've tried in various ways, but none of these works. Thanks

+1  A: 

I do it like this, but perhaps there exists a better way:

List<ListItem<MyEnum>> enumVals = new List<ListItem<MyEnum>>();

foreach( MyEnum m in Enum.GetValues (typeof(MyEnum) )
{
    enumVals.Add (new ListItem<MyEnum>(m, m.ToString());
}

myComboBox.DataSource = enumVals;
myComboBox.ValueMember = "Key";
myComboBox.DisplayMember = "Description";

Note that ListItem<T> is a custom class that I've created, which contains a Key property and a Description property.

In order to keep your property synchronized with the selected value of the combobox, you will have to : - add a databinding to the combobox, so that the SelectedValue of the combobox is bound to your property - make sure that the class which contains the property, implements INotifyPropertyChanged, so that when you change the property, the selected value of the combobox is changed as well.

myComboBox.DataBindings.Add ("SelectedValue", theBindingSource, "YourPropertyName");

and

public class TheClass : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;

   private MyEnum _myField;

   public MyEnum MyPropertyName
   {
      get { return _myField; }
      set 
      {
         if( _myField != value )
         {
             _myField = value;
             if( PropertyChanged != null )
                  PropertyChanged ("MyPropertyName");
         }
      }
   }
}
Frederik Gheysels
This would be good... but how to make this automatically syncronized with the property EnumVal? I'm using ObjectDataSource with automatic databinding.
Valerio Manfredi
Perfect, it works! Thank you!
Valerio Manfredi
A: 

http://www.syncfusion.com/FAQ/windowsforms/faq_c88c.aspx#q1124q

Ian Kemp
Nice one, but, if you want to have another description for the enums (translated description, or human readable), this is not sufficient. That's why I do it with my 'ListItem' class.In the description property, I put a translated description (coming from a resx file)
Frederik Gheysels
I've already tried this method, but this one just populates the combobox, does not syncronize with the EnumVal property.
Valerio Manfredi