繁体   English   中英

如何将结构绑定到DropDownList

[英]how to bind a struct to a DropDownList

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

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

因此,当我使用MedicalChartActions.Open时得到的整数值等于“ 0”,但是如何将其绑定到DropDownList控件以便显示变量名呢? 如何通过值获取变量名称? 例如,如果值等于“ 0”,如何返回“打开”?

除了使用结构之外,我将使用建议的类似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();    

如果是我,并且您不想访问数据库以加载可能的值,则只需将值硬编码到程序中。

首先,以声明方式创建下拉列表,如下所示:

<asp:DropDownList ID="List1" runat="server">
    <asp:ListItem Text="Open" Value="0" />
    <asp:ListItem Text="SignOff" Value="1" />
    <asp:ListItem Text="Review" Value="2" />
</asp:DropDownList>

接下来,使用List1.SelectedValue获取选定的值(0、1、2)。 请注意,这些将是字符串,因此如果您需要将它们作为数字使用,则需要使用Convert.ToInt32(List1.SelectedValue)将它们转换为整数。

您还可以创建一个枚举,这样就不必在代码中到处都硬编码一堆数字:

public enum MyEnum {Open, SignOff, Review};

现在,您可以仅将值称为MyEnum.Open而不是0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM