jame
jame

Reputation:

Associating Strings with enums in C#

I work on C# window ...vs05 ......i want to put space on enum string ....i do it below code have this.....My problem is after select a value from the combo how can i get the index number of this value .....and if i gone to edit mode then i need to show the value what is user already selected .....how to get enum selected value on basis of index number

public enum States
{
  California,
  [Description("New Mexico")]
  NewMexico,
  [Description("New York")]
  NewYork,
  [Description("South Carolina")]
  SouthCarolina,
  Tennessee,
  Washington
}

public static string GetEnumDescription(Enum value)
{
   FieldInfo fi = value.GetType().GetField(value.ToString());

   DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                     typeof(DescriptionAttribute), false);

   if (attributes != null && attributes.Length > 0)
      return attributes[0].Description;
   else
      return value.ToString();
}

public static IEnumerable<T> EnumToList<T>()
{
    Type enumType = typeof(T);

    // Can't use generic type constraints on value types,
    // so have to do check like this
    if (enumType.BaseType != typeof(Enum))
       throw new ArgumentException("T must be of type System.Enum");

    Array enumValArray = Enum.GetValues(enumType);
    List<T> enumValList = new List<T>(enumValArray.Length);

    foreach (int val in enumValArray)
    {
       enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
    }

    return enumValList;
 }

 private void Form1_Load(object sender, EventArgs e)
 {
    //cboSurveyRemarksType = new ComboBox();
    cboSurveyRemarksType.Items.Clear();
    foreach (States state in EnumToList<States>())
    {
       cboSurveyRemarksType.Items.Add(GetEnumDescription(state));
    }
 }

Upvotes: 1

Views: 1330

Answers (3)

Danish Munir
Danish Munir

Reputation: 647

Simple. You can cast the selected index (which is an integer) to the States enum. I have written a simple test method which demonstrates a few examples of using the enum that should help clear the concept:

private static void TestMethod()
    {
        foreach (States state in EnumToList<States>())
        {
            Console.Write(GetEnumDescription(state) + "\t");
            Int32 index = ((Int32)state);
            Console.Write(index.ToString() + "\t");
            States tempState = (States)index;
            Console.WriteLine(tempState.ToString());

        }
        Console.ReadLine();
    }

If you don't understand, would be happy to clarify further.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504182

So you have an integer and you want to convert it back to the enum type? Just cast it. So long as you haven't explicitly specified any values in your enum declaration, and so long as the "index" you've got is 0-based you should be able to do:

States state = (States) stateIndex;

(Note that by normal .NET naming conventions this should be called State by the way - plurals are usually reserved for flags.)

This answer is based on the text of your question rather than your code - I can't see anything in your code which really refers to an index.

Upvotes: 1

Aviad Ben Dov
Aviad Ben Dov

Reputation: 6409

  1. You could iterate through the enums available (Enum.GetValues(enumType)) and see which one has the description chosen (not the best performance but it is probably not significant for combo-boxes).
  2. You could create your own attribute, and have the index there as well (ugly in terms of coding practice)
  3. If you want to improve performance on option #1 you could pre-cache a Dictionary<String, Integer> object with the descriptions of each enum, and use that instead.

Upvotes: 2

Related Questions