Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
swdev:dotnet:enum [2011/12/02 14:02] smayr |
swdev:dotnet:enum [2011/12/02 14:11] (current) smayr |
||
---|---|---|---|
Line 38: | Line 38: | ||
</ | </ | ||
- | To query an enum value for its description: | + | To simply get the enum string equivalent (translate |
<code csharp> | <code csharp> | ||
// | // | ||
Line 47: | Line 47: | ||
return Enum.GetName(typeof(TMyColor), | return Enum.GetName(typeof(TMyColor), | ||
} | } | ||
- | </ | + | </ |
+ | |||
+ | To query an enum value for its description: | ||
+ | <code csharp> | ||
+ | using System.ComponentModel; | ||
+ | ... | ||
+ | |||
+ | // | ||
+ | // Get enum description string for the specified object. | ||
+ | // | ||
+ | public static string GetEnumDescription(Enum value) | ||
+ | { | ||
+ | System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString()); | ||
+ | |||
+ | DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), | ||
+ | |||
+ | if ((attributes != null) && (attributes.Length > 0)) | ||
+ | { | ||
+ | return attributes[0].Description; | ||
+ | } | ||
+ | else | ||
+ | { | ||
+ | return value.ToString(); | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | == Enumerate Enum for creating ListBox == | ||
+ | <code csharp> | ||
+ | /// | ||
+ | /// < | ||
+ | /// Enumerate enums to easily create a drop down list based on an enum. | ||
+ | /// Source: http:// | ||
+ | /// | ||
+ | /// Example: | ||
+ | /// DropDownList stateDropDown = new DropDownList(); | ||
+ | /// foreach (States state in EnumToList< | ||
+ | /// { | ||
+ | /// stateDropDown.Items.Add(GetEnumDescription(state)); | ||
+ | /// } | ||
+ | /// </ | ||
+ | /// < | ||
+ | /// < | ||
+ | /// | ||
+ | public static IEnumerable< | ||
+ | { | ||
+ | Type enumType = typeof(T); | ||
+ | |||
+ | // Can't use generic type constraints on value types, | ||
+ | // so have to do check like this | ||
+ | if (enumType.BaseType != typeof(Enum)) | ||
+ | { | ||
+ | throw new ArgumentException(" | ||
+ | } | ||
+ | |||
+ | Array enumValArray | ||
+ | List< | ||
+ | |||
+ | foreach (int val in enumValArray) | ||
+ | { | ||
+ | enumValList.Add((T)Enum.Parse(enumType, | ||
+ | } | ||
+ | |||
+ | return enumValList; | ||
+ | } | ||
+ | </ |