Thought I would share some code with everyone on how I do Enums, I haven't modified the Enum generator yet to do this but it shouldn't be too difficult.
We convert numerous lookup or 'type' tables to Enums to avoid doing round trips to the database, our biggest issue used to be making user friendly display text for the Enums, this is how I solved it.
Our old way of doing it was:
To populate:
comboBox1.Items.AddRange(Enum.GetNames(typeof(ExpenseItemStateEnum)));
To Convert back to Enum:
ExpenseItemStateEnum StatusFilter = (ExpenseItemStateEnum)Enum.Parse(typeof(ExpenseItemStateEnum), dxcboStatusFilter.SelectedItem.ToString(), true);
The new way uses a bit of reflection:
// required includes
using System.ComponentModel;
using System.Reflection;
public enum ExpenseItemStateEnum
{
[Description("Life, the universe and Everything")]
Everything = 0,
[Description("Waiting in the abyss")]
Waiting = 1,
[Description("Has been graciously Approved")]
Approved = 2,
[Description("Has been DENIED")]
Denied = 3
}
Then to populate I created a helper:
DevExHelper.PopulateCombo(dxcboStatusFilter.Properties, typeof(ExpenseItemStateEnum));
And to revert back to enum:
dxcboStatusFilter.SelectedItem = Utility.ConvertEnumToText(ExpenseItemStateEnum.Waiting);
The supporting code is as follows:
// This can easily be modified to work with other 3rd party combos
public static void PopulateCombo(DevExpress.XtraEditors.Repository.RepositoryItemComboBox properties, System.Type enumType)
{
foreach(Enum field in Enum.GetValues(enumType))
{
properties.Items.Add(Utility.GetEnumDisplayString(field));
}
}
public static string ConvertEnumToText(Enum enumIndex)
{
return GetEnumDisplayString(enumIndex);
}
public static string GetEnumDisplayString(Enum enumIndex)
{
string EnumString = SHIP.Framework.Utility.GetEnumValueDescription(enumIndex);
if (EnumString == null || EnumString == string.Empty)
EnumString = enumIndex.ToString();
return EnumString;
}
public static string GetEnumValueDescription(object value)
{
// Get the type from the object.
Type pobjType = value.GetType();
// Get the member on the type that corresponds to the value passed in.
FieldInfo pobjFieldInfo = pobjType.GetField(Enum.GetName(pobjType, value));
try
{
// Now get the attribute on the field.
DescriptionAttribute pobjAttribute = (DescriptionAttribute)(pobjFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false)[0]);
// Return the description.
return pobjAttribute.Description;
}
catch (System.Exception)
{
return string.Empty;
}
}
Don't know if this is useful to anyone but it solved a bunch of problems for me in making Enums human readable in our applications, note that the Description attribute is optional, if you don't want to overload its display text just leave it off and the .ToString of the enum element will be used.
John