Problem A
I have an application that uses an enum whos values aren’t nicely readable. Given a value of the enum, I’d like to get a nice, readble text name for it. I’d like the solution to be easily extensible and maintanable. What can the SDF do for me?
Problem B
I have an application with an enum and I need to populate a combobox with its value names. What can the SDF do for me?
Problem C
I have an application with an enum and I need to get a list of all of the values in the enum. What can the SDF do for me?
Solution
The solution to all of these is found in the OpenNETCF.Enum2 class. Here’s a snippet from a project I’m working on:
[Tested on the PPC 2003 Emulator with SDF 2.1]
public class DescriptionAttribute : Attribute
{
public string Description;
public DescriptionAttribute(string description)
{
Description = description;
}
}
public enum Places
{
[Description(“Missoula, Montana”)]
MissoulaMT,
[Description(“Denton, Texas”)]
DentonTX,
[Description(“Berwyn, Illinois”)]
BerwynIL,
[Description(“Frederick, Maryland”)]
FrederickMD
}
…
using System.Reflection;
using System.ComponentModel;
using OpenNETCF;
…
{
int maxPlaces = Enum2.GetValues(typeof(Places)).Length;
Places p = (Places)(new System.Random().Next(maxPlaces));
FieldInfo fi = p.GetType().GetField(Enum2.GetName(typeof(Places), p));
DescriptionAttribute desc = (DescriptionAttribute)fi.GetCustomAttributes(typeof(DescriptionAttribute), false)[0];
textBox1.Text = desc.Description;
}