例子
寫個小東西,剛好用到枚舉類型,需要顯示在DropDownList控件中。嘗試了下,用如下方法可以實現。
比如定義了一個錯誤的枚舉類型
1 public enum eErrorDetailCode 2 { 3 登陸成功 = 0, 4 登出 = 1, 5 應用錯誤 = 2, 6 成功 = 16, 7 失敗 = 17 8 }
需要引用
using System;
使用foreach循環,遍歷所有元素,
1 foreach (int myCode in Enum.GetValues(typeof(eErrorDetailCode))) 2 { 3 string strName =Enum.GetName(typeof(eErrorDetailCode), myCode);//獲取名稱 4 string strVaule = myCode.ToString();//獲取值 5 ListItem myLi = new ListItem(strName,strVaule); 6 ddlType.Items.Add(myLi);//添加到DropDownList控件 7 }
使用for循環,遍歷元素代碼示例
1 //…… 2 for (int i = 0; i < Enum.GetValues(typeof(DatasType)).Length; i++) 3 { 4 cb_DataType.Items.Add(Enum.GetValues(typeof(DatasType)).GetValue(i)); 5 } 6 //……
參考網址
[1]https://www.cnblogs.com/tianguook/archive/2013/01/30/2883443.html