从枚举

时间:2016-09-17 22:18:09

标签: c# .net combobox enums

我有一个性别枚举:

enum gender
{
    Female,
    Male
}

现在,我想使用for DisplayMember填充ComboBox,将每个枚举的字符串中的值转换为字符串(在本例中为“Female”和“Male”) 然后为ValueMember指定每个枚举的索引(在本例中为0和1)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

func setupRightBarButtonItem() {

    if navigationItem.rightBarButtonItem == nil {       
        navigationItem.rightBarButtonItem = 
            UIBarButtonItem(title: nil, style: .done, target: self, action: nil)    
    }

    if (AWSIdentityManager.default().isLoggedIn) {
            navigationItem.rightBarButtonItem!.title =     NSLocalizedString("Sign-Out", comment: "Label for the logout button.")
            navigationItem.rightBarButtonItem!.action =     #selector(MainViewController.handleLogout)
    } 
    // You probably need an `else` clause here to update the button if the user isn't logged in?
}

将这些项目添加到 //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);