2013-10-18 47 views
0

我正在構建它是其中一部分的複雜問題的一個簡單示例。將值與c中的枚舉進行比較#

爲了方便起見,有一個下拉列表,充滿了一年中的幾個月。

BindDropDown() 
{ 
    ddlColors.DataSource = GetAllMonths();//Returns a List<string> with months 
    ddlColors.DataBind(); 
    //note the drop down only have data fields no value fields no corresponding numeric values of the months. 
} 

public enum Months 
{ 
    January = 1, 
    February = 2, 
    March  = 3, 
    April  = 4, 
    May  = 5, 
    June  = 6, 
    July  = 7, 
    August = 8, 
    September = 9, 
    October = 10, 
    November = 11, 
    December = 12 
} 
  1. 從下拉選擇任何一個月份中下來後我有一些能得到相應的數值如何與存儲其數值枚舉匹配。

    例如:從下降值下降是五月,因此其對應的數字部分5.

  2. 從數據庫中,這將是數字,我一些如何必須得到枚舉的文本部分獲得價值之後。

    例如:來自數據庫的值是5,所以其相應的文本部分可能是5。

何我能否實現上述場景?

+0

這將幫助你 - [http://stackoverflow.com/questions/5129378/enums-and-combo-boxes-in-c-sharp?rq=1][1] [1]:http://stackoverflow.com/questions/5129378/enums-and-combo-boxes-in-c-sharp?rq=1 – Jardalu

回答

1

1)使用Enum.Format()通過枚舉的文本價值得到十進制值:

編輯:

var monthNumber = Enum.Format(typeof(Months), Enum.Parse(typeof(Months), ddlColors.SelectedValue.ToString()),"d"); 

2)只投整數枚舉,並調用它的toString()

var month = ((Months)value).ToString(); 
+0

它給第一個錯誤說不能將字符串轉換爲int – ankur

+0

@ankur是的,在使用Format之前,您應該將所選值轉換爲枚舉值。添加Enum.Parse(),這應該工作 – Alex

2

您可以將整數值轉換爲枚舉類型:

int value = 5; 
string month = ((Months)value).ToString(); 

或者你可以使用GetName方法:

int value = 5; 
string month = Enum.GetName(typeof(Months), value); 
0

1)您可以使用Enum.Parse()一個字符串轉換爲一個枚舉(請注意,還有一個過載這樣做的情況下不敏感的)。

(Months)Enum.Parse(typeof(Months), "May"); 

2)對於值轉換爲字符串,你只需要調用ToString()

((Months)5).ToString();