13

i have a really simple question to ask about C# and WPF. My Question will follow after this attempt of mine:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (var item in Races)
            {
                cbRace.Items.Add(item);
            }
        }
    }

    enum Races
    {
        Human=1,
        Dwarf,
        Elf,
        Orc,
        Goblin,
        Vampire,
        Centaur
    }

Ok so, my question is how will I add the values(e.g. Human,dwarf,elf....) into the combo box: cbRace? sorry I'm new to C# so i would rally appreciate it if someone can help me out :), thanks in advance.

user2061405
  • 3,141
  • 3
  • 14
  • 9

7 Answers7

26
private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        foreach (var item in Enum.GetValues(typeof(Races)))
        {
            cbRace.Items.Add(item);
        }
    }
    enum Races
    {
        Human = 1,
        Dwarf,
        Elf,
        Orc,
        Goblin,
        Vampire,
        Centaur
    }
24

You should be able to do something like this:

cbRace.DataSource = Enum.GetValues(typeof(Races));

Checkout this answer for more information on setting and retrieving the enum values.

Community
  • 1
  • 1
Crwydryn
  • 840
  • 6
  • 13
5

This would perhaps be the easiest way to set the ComboBox items:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    cbRace.ItemsSource = Enum.GetValues(typeof(Races));
    cbRace.SelectedIndex = 0;
}

It is not necessary to loop over the enum values, just set the ItemsSource property.

Clemens
  • 123,504
  • 12
  • 155
  • 268
2

This isn't a preferred solution as Clemens has already given you that but if you wanted to add in the XAML directly you could also do

<ComboBox>
    <urCode:Races>Human</urCode:Races>
    <urCode:Races>Dwarf</urCode:Races>
    <urCode:Races>Elf</urCode:Races>
</ComboBox>

you could also implment an IValueConverter that when bound to a Type, returns the Enum.GetValues

MikeT
  • 5,398
  • 3
  • 27
  • 43
2

Shortest Way to add Enum Values to Combobox in C#

class User{

public enum TYPE { EMPLOYEE, DOCTOR, ADMIN };

}

// Add this class to your form load event of Form Cunstructor

cmbUserType.Items.AddRange(Enum.GetNames(typeof(User.TYPE)));
VIKINX
  • 21
  • 1
0

use this

cbRace.Datasource = Enum.GetValues(typeof(Races));

to databind your enum to the combobox and then use selectedValue and selectedText properties of your combobox to retreive names and values;

Faaiz Khan
  • 332
  • 1
  • 4
0
cmbUserType.Items.AddRange(core.Global.ToObjectArray(Enum.GetValues(typeof(STATUS))));
public enum STATUS { INACTIVE, ACTIVE }
Termininja
  • 6,620
  • 12
  • 48
  • 49
VIKINX
  • 21
  • 1
  • I request you to please add some more context around your answer. Code-only or link-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – RBT Dec 31 '16 at 04:10