【问题标题】:Casting object from Drop Down Into Nullable type将对象从 Drop Down 转换为 Nullable 类型
【发布时间】:2012-10-09 21:43:07
【问题描述】:

我的 aspx 中有以下下拉菜单:

<aspx:DropDownList
ID="ddl1"
runat="server"/>

在代码隐藏 (C#) 中,我想从 DropDownList 中检索值。

我这样填充了我的下拉列表:

ddl1.DataSource = LocationOfData;
ddl1.DataBind();

LocationOfData 返回 CustomType 类型。编辑:CustomType 是一个枚举。

我希望能够做到以下几点:

CustomType? myvar = ddl1.Text

换句话说,使用我的 CustomType 创建一个可为空的变量并将其设置为等于下拉列表中的变量。但是我只能从 ddl1 中检索文本(字符串)的类型。

【问题讨论】:

  • CustomType的定义是什么? ?
  • 在进一步检查我的问题后,我意识到 CustomType 是一个值的枚举。
  • string 是引用类型,你只需要为值类型创建一个可为空的变量。
  • 如果 CustomType 被定义为 public enum CustomType { etc.... } 那么应该可以创建一个可为空的类型 CustomType?

标签: c# asp.net


【解决方案1】:

如果 CustomType 是 Enum,您首先必须将 ddl1.Text 解析为 Enum,然后将其转换为 Nullable 类型:

CustomType? myvar = (CustomType?) Enum.Parse(typeof(CustomType), ddl1.Text, true)

【讨论】:

    【解决方案2】:

    如果CustomTypeenum,我将在绑定到枚举的byte 值时设置下拉列表的值,而不是绑定枚举的名称。然后,当您尝试投射到 CustomType 时,您可以这样做:

    CustomType myvar = (CustomType)byte.Parse(ddl1.Text);
    

    首先进行检查以创建可为空的类型。我不知道你的标准是什么,但是:

    CustomType? myvar;
    if(/*Criteria*/)
    {
        myvar = (CustomType)byte.Parse(ddl1.Text);
    }
    else
    {
        myvar = null;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 2015-08-09
      • 2023-03-19
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2011-05-06
      相关资源
      最近更新 更多