Click here to Skip to main content
15,902,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have an Enum method like this:

C#
public enum AllCountries
{
    United_States_Of_America,
    Canada,
    Sweden,
    Japan,
    Kurdistan,
    Albania,
    Denmark,
    Finland,
    Germany,
    Great_Britain,
    South_Africa,
    Russia
}


I want to create a method
public string GetCountryString()

which can return a string containing the value of AllCountries

and also i want to use this theese countries to appear in my combobox. Please im new and have tried and tried. how can i do it?!
Posted
Comments
LanFanNinja 10-Nov-11 20:12pm    
Check my solution below.

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:

C#
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

C#
public static class ComboBoxExtentions
{
    [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
    public sealed class NameAttribute : Attribute
    {
        private readonly string m_Name;

        // This is a positional argument
        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,
 
Share this answer
 
v2
Here is the only comprehensive answer I know — done by myself: Enumeration Types do not Enumerate! Working around .NET and Language Limitations[^].

—SA
 
Share this answer
 
As far as setting the values of AllCountries to your ComboBox try this
C#
comboBox1.DataSource = Enum.GetValues(typeof(AllCountries));


And I am not sure what you mean by "which can return a string containing the value of AllCountries" but look at these two methods maybe they can help. If not maybe you can explain in more detail exactly what you want the method to do.

C#
// to return string containing all countries in AllCountries
public string GetCountryString()
{
    string[] names = Enum.GetNames(typeof(AllCountries));
    string countries = "";
    for (int i = 0; i < names.Length; i++)
    {
        countries += names[i] + " ";
    }
    return countries;
}

//to return a single value of AllCountries as a string
public string GetCountryString(AllCountries country)
{
    return country.ToString();
}


with the second method you could even pass the selectedItem of your comboBox directly to the method to receive its value as a string like so
C#
string country = GetCountryString((AllCountries)comboBox1.SelectedItem);
 
Share this answer
 
v2
Comments
Goran Shoan 11-Nov-11 15:47pm    
"comboBox1.DataSource = Enum.GetValues(typeof(AllCountries));" Unfortunately, this does not work. I do not see the countries in the combox strangely enough
LanFanNinja 11-Nov-11 20:36pm    
I do not understand what could be wrong? It should be working! I suspect something more may be wrong with your code. Where in your code are you assigning comboBox1.DataSource? Are you getting any errors? I would really need to see some more of your code to see what is wrong.
Hi, try somthing like
AllCountries country = AllCountries.Russia

Enum.GetName(Typeof(AllCountries), country);

If you are really looking for the value, you can cast it to a int. Not sure what good that would do though.

Regards,

Addy
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900