填充组合框我有性别的枚举:由枚举型
enum gender
{
Female,
Male
}
现在,我想填充在铸造字符串的枚举的每一个字符串使用DisplayMember的值组合框(在此案“女”和“男”) ,然后ValueMember的枚举的每一个索引(在这种情况下,0和1)
填充组合框我有性别的枚举:由枚举型
enum gender
{
Female,
Male
}
现在,我想填充在铸造字符串的枚举的每一个字符串使用DisplayMember的值组合框(在此案“女”和“男”) ,然后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;
}
}
添加项目到您的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);
}
的可能的复制[I如何分配在一个列表框到枚举变量选择的值?](http://stackoverflow.com/questions/17953173/如何分配值列表中选择的列表框到枚举var) – Plutonix