SDF Sample: Getting Enum Names and Values

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;

private void button1_Click(object sender, EventArgs e)
{
  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;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s