2013-07-18 46 views
2

我有一个用户控件,它实际上是一个包装下拉列表。有没有办法将这个枚举转换为正确的类型

我设置一个类型是这样的:

public Type ListType { get; set; } 

然后尝试创建下拉基于这种类型的列表项。

这是我第一次尝试:

void SetOptions() 
    { 
     DropDownList.Items.Clear(); 

     var options = Enum.GetNames(ListType).ToList(); 

     options.ThrowNullOrEmpty("options"); 

     foreach (var s in options) 
     { 
      var e = Enum.Parse(ListType, s) as Enum; 

      var item = new ListItem(e.Description(), s); 

      DropDownList.Items.Add(item); 
     } 
    } 

不过,我想知道这可能是这样做:

void SetOptions() 
    { 
     DropDownList.Items.Clear(); 

     var options = Enum.GetValues(ListType); // need to cast this to type of ListType 

     foreach (var o in options) 
     { 
      var item = new ListItem(o.Description(), o.ToString()); 

      DropDownList.Items.Add(item); 
     } 
    } 

就不能工作了我如何才能转换为值的列表正确的枚举类型。

任何想法?

回答

2

你可以这样做:

void SetOptions() 
{ 
    DropDownList.Items.Clear(); 

    var options = Enum.GetValues(ListType); // need to cast this to type of ListType 

    foreach (var o in options) 
    { 
     var item = new ListItem(o.Description(), o.ToString()); 
     item.Tag = o; 

     DropDownList.Items.Add(item); 
    } 
} 

然后你可以从任何列表项被选中的标签属性的类型。

相关问题