我将枚举绑定到asp.net 4.0 C#
中的下拉列表Enumernation是:
public enum Frequency
{
[Description("Select a frequency")]
None,
[Description("Every Hour/Mintues")]
EveryHourOrMintues,
[Description("Previous Day Data")]
PreviousDayData,
[Description("Once a week")]
OnceaWeek
}
在从下拉列表中选择值时,我想获得枚举值作为回报: 我这样做:
Frequency selectedFrequency;
foreach (Frequency f in Enum.GetValues(typeof(Frequency)))
{
if (f.ToString().Equals(this.dropDownListFrequency.SelectedValue))
{
selectedFrequency = f;
break;
}
}
通过循环遍历枚举中的每个项目(即使枚举非常小),它正在工作但绝对是一种糟糕的方式
如何检索选定的枚举,如:
Frequency selectedValue = Enum.GetValues(typeof(Frequency)).Cast<Frequency>().Select(f => f.ToString().Equals(this.dropDownListFrequency.SelectedValue));
据我所知,上面给出的代码有铸造问题。
修改 有关更多信息,请参阅下面的链接枚举列表
var frequencies = Enum.GetValues(typeof(Frequency)).Cast<Frequency>().Select(f => new
{
Text = f.ToDescriptiveTextUsingAttributes(),
Value = f.ToString()
});
this.dropDownListFrequency.DataSource=frequencies ;
this.dropDownListFrequency.DataTextField = "Text";
this.dropDownListFrequency.DataValueField = "Value";
ToDescriptiveTextUsingAttributes()是一个扩展方法,它返回枚举的Description属性的值
答案 0 :(得分:3)
如果下拉列表的值是枚举的整数表示(例如0,1,2 ...),那么您只需将其强制转换回枚举:
Frequency f = (Frequency)int.Parse(dropDownListFrequency.SelectedValue);
如果下拉列表的值是枚举字符串表示(例如&#34;无&#34;,&#34; EveryHourOrMintues&#34; ...),那么您可以使用{{1 }}:
Enum.Parse()
答案 1 :(得分:0)
您可以扩展ListItem
类以存储实际的Frequency
枚举对象,并将这些专门的ListItem
对象添加到dropDownListFrequency.Items
。当您检索dropdownListFrequency.SelectedItem
时,您可以获得实际值。
class FrequencyListItem : System.Web.UI.WebControls.ListItem.ListItem {
private Frequency _Frequency;
public Frequency Frequency {
get { return _Frequency }
}
public FrequencyListItem (Frequency f) {
this._Frequency = f;
this.Text = f.ToDescriptiveTextUsingAttributes();
this.Value = f.ToString();
}
}
由于Items
属性中的所有元素都是您的专用类,因此您可以按如下方式轻松检索枚举值:
Frequency selectedFrequency = ((FrequencyListItem )this.dropDownListFrequency.SelectedItem).Frequency;
修改:您甚至可以使用相同的绑定模型进行一些细微更改:
var frequencies = Enum.GetValues(typeof(Frequency)).Cast<Frequency>().Select(f => new FrequencyListItem()
{
//FrequencyListItem will auto set this in the constructor for you!
//Text = f.ToDescriptiveTextUsingAttributes(),
//Value = f.ToString()
});
this.dropDownListFrequency.DataSource=frequencies;
this.dropDownListFrequency.DataTextField = "Text";
this.dropDownListFrequency.DataValueField = "Value";