【问题标题】:how to bind a struct to a DropDownList如何将结构绑定到 DropDownList
【发布时间】:2011-12-04 16:02:45
【问题描述】:

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

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

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

【问题讨论】:

  • 地铁?表格? WPF?银光? ASP.NET?单触?
  • 这是一个 asp.net 网络应用程序。我更新了我的帖子。谢谢。
  • 你肯定会为此使用反射。您是否有理由必须使用结构,而不是将键/值存储在字典或其他东西中?
  • 结构部分在这里无关紧要——它们是常量这一事实更为重要。
  • @MikeChristensen,我想做的是降低数据服务器成本。我使用 struct 还是其他东西都没关系

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


【解决方案1】:

我不会使用结构,而是使用 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();    

【讨论】:

  • 谢谢,那么当我已经知道“0”时如何获得“打开”?
  • @james johnson 但是如果我们在值中有空格怎么办
【解决方案2】:

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

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

<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。

【讨论】:

  • 这里的缺点是你需要在使用枚举的任何地方复制这个 DropDownList。
  • 是的,我更喜欢您的解决方案。你发布它就像我发布我的一样。
  • @MikeChristensen 但我们如何在枚举中使用空格
  • @Dragon - 你不能。您可能希望为此绑定到字典,或者只是对字符串值进行硬编码。
  • @MikeChristensen 如果我在枚举中使用描述属性,如 public enum enumtype { [Description("new cars")] optionone = 1, [Description("used cars")] optiontwo = 2, [描述(“重型自行车”)] optionthree = 3 }
猜你喜欢
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
相关资源
最近更新 更多