Additionally for adding it to a combo, you can add Attributes to the Enum values that require spaces, when iterating over all the values in the enumeration (Enum.GetValues) you can get the attribute associates with the current value in the enumeration and print that. If the value does not have an attribute you can take the name of the value.
You can use the following:
public enum AllCountries
{
[ComboBoxExtentions.NameAttribute("United States Of America")]
United_States_Of_America,
Canada,
Sweden,
Japan,
Kurdistan,
Albania,
Denmark,
Finland,
Germany,
[ComboBoxExtentions.NameAttribute("Great Britain")]
Great_Britain,
[ComboBoxExtentions.NameAttribute("South Africa")]
South_Africa,
Russia
}
Use the following extensions to fill, read or access the combo
public static class ComboBoxExtentions
{
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public sealed class NameAttribute : Attribute
{
private readonly string m_Name;
public NameAttribute(string name)
{
m_Name = name;
}
public override string ToString()
{
return m_Name;
}
}
public static void FillWithEnumeration<T>(this ComboBox target, T defaultItem)
{
target.Items.Clear();
foreach (FieldInfo field in typeof(T).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
{
string itemName = Enum.GetName(typeof (T), field.GetValue(null));
foreach (Attribute attrib in field.GetCustomAttributes(true))
{
if(attrib.TypeId.GetType() == typeof(Enumerations.NameAttribute))
{
itemName = attrib.ToString();
break;
}
}
target.Items.Add(itemName);
}
target.SelectedIndex = target.IndexOf(defaultItem);
}
public static int IndexOf<T>(this ComboBox target, T targetitem)
{
int result = -1;
for (int i = 0; i < target.Items.Count; i++)
{
string valueName = Enum.GetName(typeof(T), targetitem);
if (target.Items[i].ToString().Equals(valueName))
{
result = i;
}
}
return result;
}
public static T EnumOfSelection<T>(this ComboBox target)
{
string name = target.Text;
if (name == null)
throw new ArgumentNullException("target.Text");
T result = default(T);
foreach (FieldInfo field in typeof(T).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
{
T item = (T)field.GetValue(null);
string itemName = Enum.GetName(typeof(T), item);
foreach (Attribute attrib in field.GetCustomAttributes(true))
{
itemName = attrib.ToString();
break;
}
if (name.Equals(itemName))
{
result = item;
break;
}
}
return result;
}
}
next all you have to do to use it is:
m_Countries.FillWithEnumeration(AllCountries.Sweden);
Note that as you are setting the default item there is no need to identify the specific enumeration from where you'd like to set the default. You could also, for clarity reasons split this and have the FillWithEnumeration only fill it and leave the default open.
Next to get the enum of the selection:
var theSelectedItem = m_Countries.EnumOfSelection<AllCountries>()
I added some code to get the index of the selection just in case you are interrested in it.
Regards,