2013-10-18 48 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();