C# WinForm 技巧六:根据Enum绑定DropDownList
一、摘要
这里主要是复制网上的,目的是为了方便自己以后查找,如有版权问题,请与我联系删除。
二、方法一
绑定
1: enum TestEnum {zero=0,one=1,two=2}2: ComboBox cbo = new ComboBox();3: cbo.DataSource = System.Enum.GetNames(typeof(TestEnum));4: TestEnum test = TestEnum .one;5: cbo.SelectedIndex = this.cbo.FindString(test.ToString());6:
取值
1: TestEnum testenum = (TestEnum)Enum.Parse(typeof(TestEnum) ,cbo.SelectedItem.ToString() ,false)
二、方法二
反射,枚举,绑定下拉框
1: public static class EnumManager<TEnum>2: {
3: private static DataTable GetDataTable()4: {
5: Type enumType = typeof(TEnum); // 获?取?类?型?对?象?6: FieldInfo[] enumFields = enumType.GetFields(); //获?取?字?段?信?息?对?象?集?合?7:
8: DataTable table = new DataTable();9: table.Columns.Add("Name", Type.GetType("System.String"));10: table.Columns.Add("Value", Type.GetType("System.Int32"));11: //遍?历?集?合?12: foreach (FieldInfo field in enumFields)13: {
14: if (!field.IsSpecialName)15: {
16: DataRow row = table.NewRow();17: row[0] = field.Name; // 获?取?字?段?文?本?值?18: row[1] = Convert.ToInt32(field.GetRawConstantValue()); // 获?取?int数?值?19: //row[1] = (int)Enum.Parse(enumType, field.Name); 也?可?以?这?样?20:
21: table.Rows.Add(row);22: }
23: }
24: return table;25: }
26:
27: public static void SetListControl(ListControl list)28: {
29: list.DataSource = GetDataTable();30: list.DataTextField = "Name";31: list.DataValueField = "Value";32: list.DataBind();33: }
34: }
使用:
1: public enum BookingStatus {2: 未?提?交? = 1,3: 已?提?交?,4: 已?取?消?,5: 已?完?成? = 66: }
7: EnumManager<BookingStauts>.SetListControl(ddlBookingStatus);8: EnumManager<TicketStatus>.SetListControl(rblTicketStatus);