C#中如何将combox中的下拉项和一个枚举中的各项进行绑定

本人想实现一个combox,将其各个下拉项设定为一个枚举中的各个项... 本人想实现一个combox,将其各个下拉项设定为一个枚举中的各个项 展开
 我来答
freeeeeewind
推荐于2017-09-12 · TA获得超过1万个赞
知道大有可为答主
回答量:3227
采纳率:94%
帮助的人:1290万
展开全部

定义一个类,将枚举和需要显示内容组合到这个类中,实现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
    }

    /// <summary>
    /// MyItem 类
    /// 将枚举和要显示的内容组合在一起
    /// </summary>
    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)运行

classfun
2012-12-06 · TA获得超过619个赞
知道小有建树答主
回答量:298
采纳率:0%
帮助的人:262万
展开全部
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

}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式