How to get the enumeration value?

I defined an enumeration like

public Enum CompanyQuarters { First=1, Second=2, Third=3, Fourth=4 } 

I bind them to a drop down list like

 ddlCompQuarter.DataSource = Enum.GetNames(typeof(CompanyQuarters)); ddlCompQuarter.DataBind(); 

Now I want to get the selected value of the dropdown list. For example, to select β€œsecond” do I like to extract 2?

This does not work

  int selectedVal = int.Parse(ddlCompQuarter.SelectedValue.ToString()); 
+4
source share
8 answers
 ActiveQuarters value = (ActiveQuarters)Enum.Parse(typeof(ActiveQuarters),ddlCompQuarter.SelectedValue.ToString()); 

or if you are using Dot Net Framework 4 or higher, see Enum.TryParse

 ActiveQuarters value; Enum.TryParse<ActiveQuarters>(ddlCompQuarter.SelectedValue.ToString(), out value); 
+7
source

Here I will show you the best way to use the enumeration:

 public enum enumVIPBusinessPlanPaymentType { [Description("Monthly")] Monthly = 1, [Description("Paid In Full (PIF)")] PaidInFull = 2, [Description("Barter")] Barter = 3 } 

and create the EnumHelper.cs class to read its value or description

 public static Int32 GetIntValue(Enum en) { Type type = en.GetType(); return TemplateControlExtension.GetInt32(null, en); } public static string GetStringNameFromValue(Enum en) { Type type = en.GetType(); MemberInfo[] info = type.GetMember(en.ToString()); if (info != null && info.Length > 0) { object[] attrs = info[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) { return ((DescriptionAttribute)attrs[0]).Description; } } return TemplateControlExtension.GetString(null, en); } 

I hope you will enjoy

+3
source
 ActiveQuarters typedValue = (ActiveQuarters)Enum.Parse(typeof(ActiveQuarters), ddlCompQuarter.SelectedValue); // If you need numeric value int numericValue = (int)typedValue; 
+2
source
 CompanyQuarters comp= (CompanyQuarters)Enum.Parse(ddlCompQuarter.SelectedValue); 
+2
source

You can use Enum.Parse

 var val = (int)(ActiveQuarters)Enum.Parse(typeof(ActiveQuarters), ddlCompQuarter.SelectedValue.ToString()); 

Also I think your code has a problem, you defined ActiveQuarters enum and bound CompanyQuarters !.

+2
source

You must cancel the way you got the names there.

http://blogs.msdn.com/b/tims/archive/2004/04/02/106310.aspx

+2
source

you need to use Enum.Parse and then you can get your enum from ComboBox

+1
source

You must set the text and value property while binding the drop-down list. For value field you can use

Enum.GetValues ​​(TypeOf (EnumProvider.CompanyQuarters))

+1
source

Source: https://habr.com/ru/post/1399993/


All Articles