枚举值使用小结

枚举值绑定到下拉框:

 

方法一:

绑定

enum TestEnum {zero=0,one=1,two=2}       
ComboBox cbo = new ComboBox();
cbo.DataSource = System.Enum.GetNames(typeof(TestEnum));

enum test=enum.one;

cbo.SelectedIndex = this.cbo.FindString(test.ToString());

取值

TestEnum testenum = (TestEnum)Enum.Parse(typeof(TestEnum) ,cbo.SelectedItem.ToString() ,false)

方法二:

foreach (var v in typeof(AA).GetFields())
{
     if (v.FieldType.IsEnum == true)
     {
          this.comboBox1.Items.Add(v.Name);
      }
}

this.comboBox1.SelectedIndex = 1;

方法三:

反射,枚举,绑定下拉框

public static class EnumManager<TEnum>
{
    private static DataTable GetDataTable()
    {
       Type enumType = typeof(TEnum); // 获取类型对象
       FieldInfo[] enumFields = enumType.GetFields();    //获取字段信息对象集合

       DataTable table = new DataTable();
       table.Columns.Add("Name", Type.GetType("System.String"));
       table.Columns.Add("Value", Type.GetType("System.Int32"));
       //遍历集合
       foreach (FieldInfo field in enumFields)
       {
           if (!field.IsSpecialName)
           {
               DataRow row = table.NewRow();
              row[0] = field.Name;   // 获取字段文本值
              row[1] = Convert.ToInt32(field.GetRawConstantValue());        // 获取int数值
              //row[1] = (int)Enum.Parse(enumType, field.Name); 也可以这样

              table.Rows.Add(row);
           }
       }
       return table;
    }

    public static void SetListControl(ListControl list)
    {
       list.DataSource = GetDataTable();
       list.DataTextField = "Name";
       list.DataValueField = "Value";
       list.DataBind();
    }
}


public enum BookingStatus {
    未提交 = 1,
    已提交,
    已取消,
    已完成 = 6
}

EnumManager<BookingStauts>.SetListControl(ddlBookingStatus);
EnumManager<TicketStatus>.SetListControl(rblTicketStatus);

 

你可能感兴趣的:(枚举)