2

I have a combobox that is bound to an enum using the following code:

cmb.ItemsSource = Enum.GetValues(typeof(DATABASE_TYPES)).Cast<DATABASE_TYPES>();

where DATABASE_TYPES is:

public enum DATABASE_TYPES
        {
            JDataStore, Access, SQLServer, H2, PostGresSQL, MySQL
        };

I have some xml that matches one of the enum values:

<property name="Database.Main.Type"
        type="databaseType"
        default="JDataStore"
        permissions="superuser">
    </property>

I am trying to programmatically set the selected item of the combobox to the default value from the xml.

I have tried:

cmb.SelectedItem = propertyNode.Attributes["default"].Value;

but this doesn't work.

Could someone please advise?

kaiz.net
  • 1,984
  • 3
  • 23
  • 31
user589195
  • 4,180
  • 13
  • 53
  • 81
  • You may want to see my answer here http://stackoverflow.com/questions/9242345/show-enum-in-a-combobox/9327548#9327548 that allows you to localize the text displayed in the combo box. – Phil Mar 23 '12 at 11:16

2 Answers2

2

You need to convert the string to an enum instance:

cmb.SelectedItem = (DATABASE_TYPES)Enum.Parse(typeof(DATABASE_TYPES), propertyNode.Attributes["default"].Value);
Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • Brilliant. I havent worked with enums much in the past. Looks like I have to get my head around them. Thanks Will mark as answer as soon as I can – user589195 Mar 23 '12 at 11:05
0

You could also get a list of strings from the enum and your code works as it is

 cmb.ItemsSource = Enum.GetNames(typeof(DATABASE_TYPES));
ionden
  • 12,536
  • 1
  • 45
  • 37