2012-03-06 144 views
4

我將它們綁定到下拉像如何獲取枚舉值?

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

現在我想獲取下拉列表選擇的值。對於例如用於選擇列表我已經定義枚舉像

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

「第二」我喜歡取2 ?

這不起作用

int selectedVal = int.Parse(ddlCompQuarter.SelectedValue.ToString()); 
+0

順便說一句,什麼是'CompanyQuarters'? (你剛剛提供了ActiveQuarters) – sll 2012-03-06 11:54:21

+0

我的不好,只是一個錯字(更正後) – 2012-03-06 12:01:34

+0

可能重複的[如何通過鍵名獲取枚舉值](http://stackoverflow.com/questions/540746/how-to-get -enum-value-by-keyname) – 2012-03-10 07:06:12

回答

7
ActiveQuarters value = (ActiveQuarters)Enum.Parse(typeof(ActiveQuarters),ddlCompQuarter.SelectedValue.ToString()); 

讓你的枚舉,或者如果您使用的是點NET框架4或更高,看到Enum.TryParse

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

感謝您的出色反應。 – 2012-03-06 17:38:51

1

你需要使用Enum.Parse,然後你可以從組合框

2
ActiveQuarters typedValue = (ActiveQuarters)Enum.Parse(typeof(ActiveQuarters), 
               ddlCompQuarter.SelectedValue); 

// If you need numeric value 
int numericValue = (int)typedValue; 
2
CompanyQuarters comp= (CompanyQuarters)Enum.Parse(ddlCompQuarter.SelectedValue); 
2

您可以使用Enum.Parse

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

而且我覺得你的代碼有問題,你定義ActiveQuarters枚舉和綁定CompanyQuarters

3

在這裏,我向您展示使用枚舉的最佳方式:

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

,並創建一個EnumHelper.cs類讀取它的值或描述

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

我希望它會像你

+0

不錯,我喜歡你的做法,很乾淨。 – 2012-03-06 18:02:47

+0

@DamienJoe:謝謝Dude ... – 2012-03-07 13:34:35

1

你必須設置文本和值屬性在綁定時下拉。 對於值字段,你可以使用

Enum.GetValues(typeof運算(EnumProvider.CompanyQuarters))