asddasd

导航

c# combobox 绑定枚举方式

https://www.cnblogs.com/northeastTycoon/p/5987734.html

 

建立一个类 :

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;
using System.ComponentModel;

namespace WindowsFormsApplication1
{
    public class EnumDescription
    {
        public static string GetEnumDesc(Enum e)
        {
            FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
            DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.
                GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (EnumAttributes.Length > 0)
            {
                return EnumAttributes[0].Description;
            }
            return e.ToString();
        }
    }
}
复制代码

 页面代码 :

 

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           // Init();
            Init1();
        }

        public  void Init()
        {
            comboBox1.DataSource = System.Enum.GetNames(typeof(ENUm_Type));
        }

        /// <summary>
        /// 反射邦定枚举
        /// </summary>
        private void Init1()
        {
            Array arrs = System.Enum.GetValues(typeof(ENUm_Type));    // 获取枚举的所有值
            DataTable dt = new DataTable();
            dt.Columns.Add("String", Type.GetType("System.String"));
            dt.Columns.Add("Value", typeof(int));
            foreach (var arr in arrs)
            {
                string strText = EnumDescription.GetEnumDesc((ENUm_Type)arr);
                DataRow aRow = dt.NewRow();
                aRow[0] = strText;
                aRow[1] = (int)arr;
                dt.Rows.Add(aRow);
            }

            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "String";
            comboBox1.ValueMember = "Value";
        }


        


        private void button1_Click(object sender, EventArgs e)
        {
            // 第一种实现方式
            //ENUm_Type eT = ENUm_Type.tet_1;
            //comboBox1.SelectedIndex = comboBox1.FindString(eT.ToString());

            //string str  =   comboBox1.SelectedItem.ToString();

            // 第二种实现方式
            int a = comboBox1.SelectedIndex;
            System.Diagnostics.Trace.WriteLine(comboBox1.SelectedItem);
            DataRowView dr = (DataRowView)(comboBox1.SelectedItem);
            ENUm_Type aE = (ENUm_Type)(dr.Row[1]);
        }


        public enum ENUm_Type
        {
            [Description("tet_1")]
             tet_1 = 1,
            [Description("tet_2")]
            tet_2 = 2,
            [Description("tet_3")]
            tet_3 = 3,
        }
    }


}

posted on 2020-11-25 17:01  asddasd  阅读(499)  评论(0编辑  收藏  举报