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

前端 未结 28 2172
心在旅途
心在旅途 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:45

    Let's say you have the following enum

    public enum Numbers {Zero = 0, One, Two};
    

    You need to have a struct to map those values to a string:

    public struct EntityName
    {
        public Numbers _num;
        public string _caption;
    
        public EntityName(Numbers type, string caption)
        {
            _num = type;
            _caption = caption;
        }
    
        public Numbers GetNumber() 
        {
            return _num;
        }
    
        public override string ToString()
        {
            return _caption;
        }
    }
    

    Now return an array of objects with all the enums mapped to a string:

    public object[] GetNumberNameRange()
    {
        return new object[]
        {
            new EntityName(Number.Zero, "Zero is chosen"),
            new EntityName(Number.One, "One is chosen"),
            new EntityName(Number.Two, "Two is chosen")
        };
    }
    

    And use the following to populate your combo box:

    ComboBox numberCB = new ComboBox();
    numberCB.Items.AddRange(GetNumberNameRange());
    

    Create a function to retrieve the enum type just in case you want to pass it to a function

    public Numbers GetConversionType() 
    {
        EntityName type = (EntityName)numberComboBox.SelectedItem;
        return type.GetNumber();           
    }
    

    and then you should be ok :)

提交回复
热议问题