0

I seem to be stuck trying to convert a collection of ListBox items to Enum.

Here is my code

 ChannelCodeType[] ChannelCodes = lbSearch.SelectedItems;


public enum ChannelCodeType {

        /// <remarks/>
        XYZ1,

        /// <remarks/>
        XYZ1_KIDS,

        /// <remarks/>
        XYZ1_PRIME,

        /// <remarks/>
        XYZ13,

        /// <remarks/>
        XYZ14,
    }

I am trying to pass the values (selecteditems) back to the ChannelCodes

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Usher
  • 2,146
  • 9
  • 43
  • 81
  • 1
    The way you put this makes no sense. You want to set an array of an `enum` type to a set of values from a dropdown of some sort. You don't want to pass anything to an enum. – John Saunders Jun 20 '14 at 02:13

1 Answers1

4

The SelectedItems property is most likely a collection of type Object.

Try casting the collection back to the original type:

ChannelCodeType[] ChannelCodes
    = lbSearch.SelectedItems.Cast<ChannelCodeType>().ToArray();

I'm assuming lbSearch is a ListBox and that it's been filled with ChannelCodeType values.


If Baldrick is right, and you've got string representations of the ChannelCodeType enum values, then you may need to modify the code to parse the strings back to the original enum:

ChannelCodeType[] ChannelCodes
  = lbSearch.SelectedItems
            .Cast<string>()
            .Select(c => (ChannelCodeType)Enum.Parse(typeof(ChannelCodeType), c))
            .ToArray();
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • 1
    If I had to *guess*, I'd suggest the OP *might* have the string representations of the enum as the underlying object in the ListBox. In which case, you'd need to do something like this: http://stackoverflow.com/questions/16100/how-do-i-convert-a-string-to-an-enum-in-c – Baldrick Jun 20 '14 at 02:12
  • @GrantWinney, i missed the cast and try to pass the value,that's why it keeps complaining. thanks a lot Grant Winney. – Usher Jun 20 '14 at 02:57