定义一个类,将枚举和需要显示内容组合到这个类中,实现ComboBox中的下拉项与枚举的绑定。
实现方法如下
(1)在Visual Studio中创建一个“Windows 窗体应用程序”项目
(2)在Form1上布置一个ComboBox控件
(3)窗体代码Form1.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 将comboBox1设置为下拉列表框风格
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
// 添加项目
MyItem item = new MyItem("吃苹果", Fruit.Apple);
comboBox1.Items.Add(item);
item = new MyItem("剥桔子", Fruit.Orange);
comboBox1.Items.Add(item);
item = new MyItem("啃香蕉", Fruit.Banana);
comboBox1.Items.Add(item);
item = new MyItem("削梨子", Fruit.Pear);
comboBox1.Items.Add(item);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MyItem item = comboBox1.SelectedItem as MyItem;
MessageBox.Show(item.Description +
"!枚举值:"+ item.Fruit.ToString());
}
}
// 枚举
enum Fruit
{
Apple = 10,
Orange = 12,
Banana = 23,
Pear = 100
}
///
/// MyItem 类
/// 将枚举和要显示的内容组合在一起
///
class MyItem
{
string description;
Fruit fruit;
public MyItem(string description, Fruit fruit)
{
this.description = description;
this.fruit = fruit;
}
public string Description { get { return this.description; } }
public Fruit Fruit { get { return this.fruit; } }
public override string ToString()
{
return description;
}
}
}
(4)运行
Array temp = Enum.GetValues(typeof(_enum_));//_enum_需要绑定的枚举
for (int i = 0; i < temp.Length; i++)
{
string info = temp.GetValue(i).ToString();
combox.items.add(info);//将每一项添加到combox
}