Lookups powered by Enums
I want to be able to maintain lookup tables in databases purely for reporting and similar applications. I like enums in code instead of retrieving lookup data as they’re integer comparisons, they eliminate the database hit, and they are far more legible. Here’s how to get the data you need to populate lists, dropdowns etc based on enums.
I declared a sample Titles enum just to test with:
public enum Titles
{
Mr = 1,
Mrs = 2,
Dr = 3,
Hon = 4,
Miss = 5,
Master = 6
}
I then get the type of the enum, and then do a foreach loop to get all the values available. Enum.GetValues retrieves all the values in the enum. The behaviour of ToString and ToInt mean that it is possible to populate combos straight off of enums.
class Program
{
static void Main(string[] args)
{
Enumerate();
}�br /> private static void Enumerate()
{
Type title = typeof(Titles);
foreach (Titles item in Enum.GetValues(title))
{
Console.WriteLine(String.Format (“Title number {0} is \”{1}\”",
Convert.ToInt16(item), item.ToString()));
}
Console.ReadKey();
}
}
October 1st, 2006 at 2:53 am
Seth has *perfected* this idea, and has put up the source on his blog here. His implementation will let you specify user-friendly text as a description of each enum, and use that to populate from.