public enum Project
{
Regular,
Important,
Critical=6,
Super
}
Console.WriteLine(Project.Regular); //Regular
Console.WriteLine(Convert.ToInt32(Project.Regular)); //0
Console.WriteLine((int)Project.Regular); //0
From INT
Console.WriteLine(Project)6; //Critical
From String
Console.WriteLine((Project)Enum.Parse(typeof(Project), "Important")); //Important
Make it as array and change it to Listitem(Both is String)
Enum.GetNames(typeof(Project)).Select(x => new ListItem(x));
Make it as array and change it to Listitem(Value int , Text is String)
Enum.GetNames(typeof(Project)).Select(x => new ListItem {
Value= Convert.ToInt32((Enum. Parse(typeof(Project),x))).ToString(),
Text = x
});
*Remember
rblStatus.DataValueField = "Value";
rblStatus.DataTextField = "Text";
public class EnumUtils<T>
{
public static string GetDescription(T enumValue, string defaultDesc)
{
string desc = defaultDesc;
FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
if (null != fi)
{
object[] attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attrs != null && attrs.Length > 0)
{
object attr = attrs.FirstOrDefault(p => p.GetType().Name == typeof(DescriptionAttribute).Name);
if (attr != null)
{
desc = ((DescriptionAttribute)attr).Description;
}
}
}
return desc;
}
public static List<Enum> ToEnumList()
{
return Enum.GetValues(typeof(T)).Cast<Enum>().ToList();
}
public static List<string> ToNameList()
{
return Enum.GetNames(typeof(T)).ToList();
}
public static T FromName(string name)
{
return (T)Enum.Parse(typeof(T), name);
}
public static T FromDescription(string description)
{
Type t = typeof(T);
T result = default(T);
foreach (FieldInfo fi in t.GetFields())
{
object[] attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attrs != null && attrs.Length > 0)
{
foreach (DescriptionAttribute attr in attrs)
{
if (attr.Description.Equals(description))
{
result = (T)fi.GetValue(null);
}
}
}
}
return result;
}
}
//Calling the Mehod
public static List<SelectListItem> TransRiskLevel()
{
var list = new List<SelectListItem>();
var actionList = EnumUtils<TransRiskLevel>.ToValueList<TransRiskLevel>();
foreach (var action in actionList)
{
list.Add(new SelectListItem
{
Text = EnumUtils<TransRiskLevel>.GetDescription(action),
Value = ((int)action).ToString()
});
}
return list;
}