c# - 如何将结构绑定(bind)到 DropDownList

标签 c# asp.net data-binding drop-down-menu struct

我在我的 ASP.NET 应用程序中使用 C#,并且有一些我不想存储在数据库中的属性。我想为这些属性使用定义的结构,如下所示:

public struct MedicalChartActions
    {
        public const int Open = 0;
        public const int SignOff = 1;
        public const int Review = 2;
    }

所以当我使用 MedicalChartActions.Open 时我得到了等于“0”的整数值,但是我如何将它绑定(bind)到 DropDownList 控件以便我可以显示变量名称?如何通过值获取变量名?例如,如果值为“0”,我如何返回“Open”?

最佳答案

我不使用结构,而是使用像 SLaks 建议的枚举器。

public enum MedicalChartActions : int
{ 
    Open = 0,
    SignOff = 1, 
    Review = 2
} 

然后你可以这样做:

var actions = from MedicalChartActions action in Enum.GetValues(typeof(MedicalChartActions))
              select new 
              { 
                  Name = action.ToString(), 
                  Value = (int)action; 
              };

DropDownList1.DataSource = actions.ToList();
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();

编辑

一旦将结构更改为枚举,就可以像这样从值中获取名称:

int value = 0;
MedicalChartActions action = (MedicalChartActions)value;

string actionName = action.ToString();    

关于c# - 如何将结构绑定(bind)到 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7715717/

相关文章:

c# - 如何以编程方式检索 HTML 服务器控件的样式?

c# - 为什么 EPPLUS 删除了我的 excel 文件?

C# 使用 IComparer 对 x 列进行排序

asp.net - 未显示登录用户名

javascript - 使用路由在 AngularJS 应用程序中进行数据绑定(bind)

python - Python 中的数据绑定(bind)?

wpf - 如何将工厂用于DataGrid.CanUserAddRows = true

c# - 如何使用 JSON.NET 将带有空值的 json 数组反序列化为不可空的 int 列表?

javascript - 将字符串参数传递给 JavaScript 函数

c# - System.ComponentModel - 忽略属性