Reputation: 3401
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.
Upvotes: 15
Views: 50434
Reputation:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cbRace.ItemsSource = Enum.GetValues(typeof(Races));
}
Upvotes: 28
Reputation: 840
You should be able to do something like this:
cbRace.ItemsSource = Enum.GetValues(typeof(Races));
Checkout this answer for more information on setting and retrieving the enum values.
Upvotes: 24
Reputation: 2979
Given something like
public class ComboBoxItem
{
public ComboBoxItem(int id, string text)
{
Id = id;
Text = text;
}
public int Id { get; set; }
public string Text { get; set; }
public override string ToString() => Text;
}
you could use
public static IEnumerable<ComboBoxItem> GetAsComboBoxItems<TEnum>()
{
foreach (var enumValue in Enum.GetValues(typeof(TEnum)))
{
yield return new ComboBoxItem((int)enumValue, enumValue.ToString());
}
}
and then
cbRace.DataSource = GetAsComboBoxItems<Races>().ToList();
Upvotes: 0
Reputation: 31
cmbUserType.Items.AddRange(core.Global.ToObjectArray(Enum.GetValues(typeof(STATUS))));
public enum STATUS { INACTIVE, ACTIVE }
Upvotes: 0
Reputation: 31
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)));
Upvotes: 3
Reputation: 5500
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
Upvotes: 2
Reputation: 128060
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.
Upvotes: 6
Reputation: 332
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;
Upvotes: 0