你如何绑定枚举到DropDownList控件在ASP.NET中? [英] How do you bind an Enum to a DropDownList control in ASP.NET?

查看:181
本文介绍了你如何绑定枚举到DropDownList控件在ASP.NET中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下简单枚举:

Let's say I have the following simple enum:

enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
}

我如何可以将绑定该枚举到DropDownList控件,这样的描述显示在列表以及检索相关的数值(1,2,3),一旦一个选项被选中?

How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?

推荐答案

我可能不会绑定,因为它是一个枚举,它会经过编译的时候(除非我是不会改变的数据米有那些的 stoopid 的时刻)之一。

I probably wouldn't bind the data as it's an enum, and it won't change after compile time (unless I'm having one of those stoopid moments).

只是为了更好地遍历枚举:

Better just to iterate through the enum:

Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))

For i As Integer = 0 To itemNames.Length - 1
    Dim item As New ListItem(itemNames(i), itemValues(i))
    dropdownlist.Items.Add(item)
Next

或者C#中的相同

Or the same in C#

Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));

for (int i = 0; i <= itemNames.Length - 1 ; i++) {
    ListItem item = new ListItem(itemNames[i], itemValues[i]);
    dropdownlist.Items.Add(item);
}

这篇关于你如何绑定枚举到DropDownList控件在ASP.NET中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆