利用发射 下拉列表绑定枚举

  public static DataTable GetDataTable(Type enumType)
        {
           // NameValueCollection nvc = new NameValueCollection();
            Type typeDescription = typeof(DescriptionAttribute);
            System.Reflection.FieldInfo[] fields = enumType.GetFields();
            string strText = string.Empty;
            string strValue = string.Empty;
            DataTable table = new DataTable();
            table.Columns.Add("Name", Type.GetType("System.String"));
            table.Columns.Add("Value", Type.GetType("System.Int32"));

            foreach(FieldInfo field in fields)
            {
                if(field.FieldType.IsEnum == true)
                {
                    DataRow row = table.NewRow();

                    strValue = ((int)enumType.InvokeMember(field.Name,BindingFlags.GetField,null,null,   null)).ToString();

                    row[1] = strValue;
                   object[] arr = field.GetCustomAttributes(typeDescription,true);
                  if (arr.Length> 0)
                    {
                        DescriptionAttribute aa = (DescriptionAttribute)arr[0];
                     
                        row[0] = aa.Description;
                    }
                    else
                    {
                        row[0] = field.Name;
                    }
                    //nvc.Add(strText,strValue);
                    table.Rows.Add(row);

                }
            }
            return table;
         }

posted @ 2012-06-29 11:04  AlanCoder  阅读(184)  评论(0编辑  收藏  举报
View Code