Esempio n. 1
0
        /// <summary>
        /// Get a table by Enum,the table has Text and Value columns
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static DataTable GetEnumTable(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException();
            }

            DataTable dt = new DataTable();

            dt.Columns.Add("Text", typeof(System.String));
            dt.Columns.Add("Value", typeof(System.String));

            Type typeDescription = typeof(TextAttribute);

            FieldInfo[] fields = enumType.GetFields();

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

                    dr["Value"] = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();

                    object[] arr = field.GetCustomAttributes(typeDescription, true);
                    if (arr.Length > 0)
                    {
                        TextAttribute aa = (TextAttribute)arr[0];
                        dr["Text"] = aa.Text;
                    }
                    else
                    {
                        dr["Text"] = field.Name;
                    }
                    dt.Rows.Add(dr);
                }
            }

            return(dt);
        }
Esempio n. 2
0
        public static string GetEnumTextVal(string enumName, Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException();
            }

            string textVal = "";

            Type      typeDescription = typeof(TextAttribute);
            FieldInfo fieldInfo       = enumType.GetField(enumName);

            if (fieldInfo != null)
            {
                object[] arr = fieldInfo.GetCustomAttributes(typeDescription, true);
                if (arr.Length > 0)
                {
                    TextAttribute textAttribute = (TextAttribute)arr[0];
                    textVal = textAttribute.Text;
                }
            }

            return(textVal);
        }