C# 枚举绑定到ComboBox


1.准备信息

1.1 定义使用的枚举

public enum E_ModuleType
{
    [Description("YD-2040:电力监控仪表")]
    E_YD_2040 = 1,
    [Description("YD-2200:电力监控仪表")]
    E_YD_2200 = 2,
    [Description("HDESC-121:节能控制器")]
    E_HDESC121 = 3,
}

 

1.2 定义枚举的描述获取类

需要添加的PACKAGE:

using System.Reflection;
using System.ComponentModel;

 

public class EnumTextByDescription
{
    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();
    }
}
 
2.使用方法

 

2.1 方法1

绑定

private void InitCombobox()
{
    comboBox1.DataSource = System.Enum.GetNames(typeof(E_ModuleType));
}

使用

privte voidbutton1_Click(objectsender, EventArgse)
{
    // 选择
   
E_ModuleTypeeT= E_ModuleType.E_YD_2200;
    comboBox1.SelectedIndex= comboBox1.FindString(eT.ToString());

    // 获取
   
E_ModuleTypeeTGet= (E_ModuleType)Enum.Parse(typeof(E_ModuleType), comboBox1.SelectedItem.ToString(), false);
}

2.2 方法2:

反射,枚举,绑定下拉框

private void InitCombobox()
{
    Array arr = System.Enum.GetValues(typeof(E_ModuleType));    // 获取枚举的所有值
    DataTable dt = new DataTable();
    dt.Columns.Add("String", Type.GetType("System.String"));
    dt.Columns.Add("Value", typeof(int));
    foreach (var a in arr)
    {
        string strText = EnumTextByDescription.GetEnumDesc((E_ModuleType)a);
        DataRow aRow = dt.NewRow();
        aRow[0] = strText;
        aRow[1] = (int)a;

        dt.Rows.Add(aRow);
    }

    comboBox1.DataSource = dt;
    comboBox1.DisplayMember = "String";
    comboBox1.ValueMember = "Value";
}
使用
private void button2_Click(object sender, EventArgs e)
{
    int a = comboBox1.SelectedIndex;
    System.Diagnostics.Trace.WriteLine(comboBox1.SelectedItem);
    DataRowView dr = (DataRowView)(comboBox1.SelectedItem);
    E_ModuleType aE = (E_ModuleType)(dr.Row[1]);
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM