简体   繁体   English

从枚举填充ComboBox

[英]Populating a ComboBox from an enum

I have an enum for gender: 我有一个性别清单:

enum gender
{
    Female,
    Male
}

Now, I want to populate a ComboBox using for DisplayMember the value in string of each one of the enums casted to string (in this case "Female" and "Male") and then for ValueMember the index of each one of the enums (in this case 0 and 1) 现在,我想填充一个ComboBox,使用DisplayMember中每个强制转换为字符串的枚举的字符串值(在这种情况下为“ Female”和“ Male”),然后对于ValueMember使用每个枚举的索引(这种情况下0和1)

    enum gender
    {
        Female,
        Male
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (var value in Enum.GetValues(typeof(gender)))
        {
            genderComboBox.Items.Add(value.ToString());
        }
    }
    //Define the template for storing the items that should be added to your combobox
    public class ComboboxItem
    {
        public string Text { get; set; }

        public object Value { get; set; }

        public override string ToString()
        {
            return Text;
        }
    }

Add the items to your ComboBox like this: 将项目添加到您的ComboBox如下所示:

       //Get the items in the proper format
        var items = Enum.GetValues(typeof(gender)).Cast<gender>().Select(i => new ComboboxItem()
        { Text = Enum.GetName(typeof(gender), i), Value = (int)i}).ToArray<ComboboxItem>();
        //Add the items to your combobox (given that it's called comboBox1)
        comboBox1.Items.AddRange(items);

Example use case: 用例示例:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

        //Example usage: Assuming you have a multiline TextBox named textBox1
        textBox1.Text += String.Format("selected text: {0}, value: {1} \n", ((ComboboxItem)comboBox1.SelectedItem).Text, ((ComboboxItem)comboBox1.SelectedItem).Value);

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM