简体   繁体   中英

Casting enum value to int when binding to dropdown using reflection

I have some code that binds an enumeration to a dropdown list, however, I'd like build the dropdown to take the integer value from the enum for the value and the description attribute for the text.

I tried defining the kvPairList as a int/string and casting enumValue and an (int) I also tried converting.toInt32

Ideas?

<select name="DropDownList1" id="DropDownList1"> 
  <option value="1">Option 1</option> 
  <option value="2">Option 2</option> 
  <option value="3">Option 3/option>  
</select

Enum:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;

    namespace constants
    {
        public enum Options : int
        {

            [Description("Option 1")]
            Option1 = 1,
            [Description("Option 2")]
            Option2 = 3,
            [Description("Option 3")]
            Option3 = 3
        }
    }

Class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ComponentModel;
using System.Reflection;

public class EnumDescription
{
    public static string GetDescription(System.Enum value)
    {
        FieldInfo FieldInfo = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])FieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

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

    public static List<KeyValuePair<string, string>> GetValuesAndDescription(System.Type enumType)
    {
        List<KeyValuePair<string, string>> kvPairList = new List<KeyValuePair<string, string>>();

        foreach (System.Enum enumValue in System.Enum.GetValues(enumType))
        {
            kvPairList.Add(new KeyValuePair<string, string>(enumValue.ToString(), GetDescription(enumValue)));
        }

        return kvPairList;
    }

}

You need to actually cast it to an int before getting the string representation. Otherwise you are getting the representation of the enumeration, rather than the integer.

kvPairList.Add(new KeyValuePair<string, string>(((int)enumValue).ToString(), GetDescription(enumValue)));

Since the value is of type System.Enum and not the underlying enum, a cast won't work. You could otherwise use the appropriate Convert method.

kvPairList.Add(new KeyValuePair<string, string>(Convert.ToInt32(enumValue).ToString(), GetDescription(enumValue)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM