How to link enum enumeration with winform combobox using objectdatasource

I bind the class to the window form using the object's data source: binding simple properties to text fields works fine, but I also need to bind enumeration properties to fields, for example:

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

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

How to do this using a binding source? I tried differently, but none of these works. Thanks

+1
source share
2 answers

I do it this way, but maybe there is 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>this is a custom class I created that contains the Key property and the Description property.

, : - , SelectedValue combobox - , , , INotifyPropertyChanged, combobox.

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

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");
         }
      }
   }
}
+3

. Yahoo , , . , , . ...

, :

public enum MyEnum{
  ItemOne,
  ItemTwo,
}

, :

myCombo.DataSource = System.Enum.GetValues(typeof(MyEnum));

- , , :

class MyObject{
  private MyEnum myEnumProperty;
  public MyEnum MyEnumProperty{get {return myEnumProperty;}}
}
MyObject myObj = new MyObject();
myCombo.DataBindings.Add(new Binding("SelectedIndex", myObject, "MyEnumProperty");
+1

All Articles