【问题标题】:Populating a ComboBox from an enum从枚举填充 ComboBox
【发布时间】:2016-09-17 22:18:08
【问题描述】:

我有一个性别枚举:

enum gender
{
    Female,
    Male
}

现在,我想为 DisplayMember 填充一个组合框,将每个枚举的字符串值转换为字符串(在本例中为“女性”和“男性”) 然后是 ValueMember 每个枚举的索引(在本例中为 0 和 1)

【问题讨论】:

标签: c# .net combobox enums


【解决方案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());
        }
    }

【讨论】:

    【解决方案2】:
        //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;
            }
        }
    

    像这样将项目添加到您的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);
    

    示例用例:

        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);
    
        }
    

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 2018-10-27
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多