gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:34:10 26 4
gpt4 key购买 nike

我在我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com