填充組合框我有性別的枚舉:由枚舉型
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