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