Reputation: 1163
I want to populate a combo box with all of the available item types in my struct ItemTypes
:
public enum ItemTypes
{
Ore,
Ice,
Mineral,
Pi
}
In order not to add a new item type in 2 places if I do have to add one eventually (not likely, but still could happen), I want to use reflection to populate that combo box instead of manually adding each item type in a list. This is how I do it:
private void InitItemTypeComboBox()
{
ComboBoxItemTypes = new List<String>();
foreach (var itemType in typeof(EveItem.ItemTypes).GetFields())
{
ComboBoxItemTypes.Add(itemType.Name);
}
SelectedComboBoxItemType = ComboBoxItemTypes.ElementAt(0);
}
Unfortunately, the GetFields()
and itemType.Name
functions return not only the 4 item types in my struct, it also returns value__
as first field, so I have an extra element in my combo box that I do not want.
I have tried using the BindingFlags.DeclaredOnly
, BindingFlags.Public
and BindingFlags.Instance
flags of the GetFields()
together, but it still returns that first value__
element that I don't want.
Is there a way to specify that I do not want this element other than by manually skipping the first element returned by typeof(EveItem.ItemTypes).GetFields()
?
EDIT:
If it changes anything, my ItemTypes
struct is nested inside another one of my public classes.
Upvotes: 0
Views: 411
Reputation: 48240
An easiest way to get values from an enum is to use a built-in Enum.GetValues
method.
https://msdn.microsoft.com/en-us/library/system.enum.getvalues%28v=vs.100%29.aspx
Upvotes: 1
Reputation: 111870
You can use BindingFlags.Static
(see for example http://goo.gl/w3VndT)
So
typeof(EveItem.ItemTypes).GetFields(BindingFlags.Static | BindingFlags.Public)
Upvotes: 1
Reputation: 3726
you should use :var t = typeof(ItemTypes).GetFields().Where(k => k.IsLiteral == true);
Upvotes: 2