Binding an enum to a WinForms combo box, and then setting it

前端 未结 28 2009
心在旅途
心在旅途 2020-11-28 04:33

a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:

comboBox1.DataSource = Enum.GetValues(typeof(MyE         


        
相关标签:
28条回答
  • 2020-11-28 04:55

    This worked for me:

    comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
    comboBox1.SelectedIndex = comboBox1.FindStringExact(MyEnum.something.ToString());
    
    0 讨论(0)
  • 2020-11-28 04:56

    Try this:

    // fill list
    MyEnumDropDownList.DataSource = Enum.GetValues(typeof(MyEnum));
    
    // binding
    MyEnumDropDownList.DataBindings.Add(new Binding("SelectedValue", StoreObject, "StoreObjectMyEnumField"));
    

    StoreObject is my object example with StoreObjectMyEnumField property for store MyEnum value.

    0 讨论(0)
  • 2020-11-28 04:56

    You could use the "FindString.." functions:

    Public Class Form1
        Public Enum Test
            pete
            jack
            fran
            bill
        End Enum
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            ComboBox1.DataSource = [Enum].GetValues(GetType(Test))
            ComboBox1.SelectedIndex = ComboBox1.FindStringExact("jack")
            ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Test.jack.ToString())
            ComboBox1.SelectedIndex = ComboBox1.FindStringExact([Enum].GetName(GetType(Test), Test.jack))
            ComboBox1.SelectedItem = Test.bill
        End Sub
    End Class
    
    0 讨论(0)
  • 2020-11-28 04:56

    You can use a list of KeyValuePair values as the datasource for the combobox. You will need a helper method where you can specify the enum type and it returns IEnumerable> where int is the value of enum and string is the name of the enum value. In your combobox, set, DisplayMember property to 'Key' and ValueMember property to 'Value'. Value and Key are public properties of KeyValuePair structure. Then when you set SelectedItem property to an enum value like you are doing, it should work.

    0 讨论(0)
  • 2020-11-28 04:56

    only use casting this way:

    if((YouEnum)ComboBoxControl.SelectedItem == YouEnum.Español)
    {
       //TODO: type you code here
    }
    
    0 讨论(0)
  • 2020-11-28 04:57

    The code

    comboBox1.SelectedItem = MyEnum.Something;
    

    is ok, the problem must reside in the DataBinding. DataBinding assignments occur after the constructor, mainly the first time the combobox is shown. Try to set the value in the Load event. For example, add this code:

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        comboBox1.SelectedItem = MyEnum.Something;
    }
    

    And check if it works.

    0 讨论(0)
提交回复
热议问题