有时,需要将一个枚举类型绑定到DropDownList供用户选择,这主要是Enum.GetNames和Enum.GetValues的使用。

方法如下:

绑定Enum到DropDownList控件的方法            dropdownlist.DataSource = Enum.GetNames(typeof(YourEnumType));
绑定Enum到DropDownList控件的方法            dropdownlist.DataBind();

这样,可以直接将Enum绑定到DropDownList控件上,不过有个缺点是,DropDownList的value也是枚举的名称而不是枚举代表的数值,有时,我是需要枚举数值的,因为一般以数值方式存储到数据库。这时可以使用下面的方法:

绑定Enum到DropDownList控件的方法            string[] names = Enum.GetNames(typeof(YourEnumType));
绑定Enum到DropDownList控件的方法            
int[] values = (int[])Enum.GetValues(typeof(YourEnumType));
绑定Enum到DropDownList控件的方法            
for (int i = 0; i < names.Length; i++)

中文的时候你可以这样写:
绑定Enum到DropDownList控件的方法    public enum A
    }

你甚至可以这样写:
绑定Enum到DropDownList控件的方法    public enum 我的枚举
    }



相关文章:

  • 2022-12-23
  • 2022-01-23
  • 2021-06-04
  • 2021-10-06
  • 2021-09-28
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-15
  • 2022-12-23
  • 2021-11-02
  • 2021-06-24
  • 2021-08-27
相关资源
相似解决方案