Compact Framework: Binding a ComboBox to an Enumerable type

I’m working on a graphics conversion utility for use in my mobile projects as well as for a friend’s web based application.  My goal has been to write code that I can run both on the compact framework as well as on the full-featured version of the .Net framework.

Let’s say we have an Enumerable type in our class as follows:

   class GoodEating
           public enum Fixins
                    Bacon = 0,
                    Cheese = 1,
                    BBQ = 2

Normally, it would be as simple as using the following C# code to bind an enumerable to a comboBox:

   combo1.DataSource = Enum.GetValues( typeof ( Fixins ) );

As I’m sure you are aware, many things available in the full .Net framework were cut from the compact framework to make it, well… compact. So, here’s what we need to do to bind a combobox to an enumerable type:

   // Create a List of type <string> to put our results in to.
   List<string> results = new List<string>();
   // iterate the items in the Enumerable type via ordinal reference.
   for (int i = 0; Enum.IsDefined( typeof( GoodEating.Fixins ), i); i++)
      // Convert the name of the type member to a string and add it
      //   to our List called ‘result’
      results.Add( ( (GoodEating.Fixins) i ).ToString() );       
   // Bind the Datasource of our combobox to the List called ‘results’.
   combo1.DataSource = results;

Not too bad!  Now that we have our combobox bound to the list, it looks like this:

Our program now has data the user can select.  Since we went through the trouble of creating an enumerable type, it’s expected that we will want to pass the value of the selection back to a method as the type.  It’s even more simple to get the value back out.  One line of code, a bit simpler than you might think:  

   // Pass our enumerable type ‘Fixins’ into our Method ‘PutToppingsOnABun’
   // Since the Enumerable types can be referenced via value, the
   //    SelectedIndex value corresponds to the value of the enums in the class.
   //    We’re casting the value (integer) to the corresponding value of the type
   //    in the enum. For instance:
   // Value   Type
   //  —–   ——–
   //     0       Bacon
   //     1       Cheese
   //     2       BBQ
   clsGoodEats.PutToppingsOnABun( ( GoodEating.Fixins ) combo1.SelectedIndex);

Pretty easy, eh?