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;
}
}