【问题标题】:Binding a nullable int to an asp:TextBox将可为空的 int 绑定到 asp:TextBox
【发布时间】:2010-03-25 22:35:09
【问题描述】:

我的数据源 (ObjectDataSource) 中有一个属性 int? MyProperty 作为成员。我可以将它绑定到一个文本框,比如

<asp:TextBox ID="MyTextBox" runat="server" Text='<%# Bind("MyProperty") %>' />

基本上,我希望在 TextBox 中将 null 值显示为空白 "",并将数字作为数字。如果 TextBox 为空,MyProperty 应设置为 null。如果 TextBox 中有一个数字,MyProperty 应该设置为这个数字。

如果我尝试它,我会得到一个异常:“Blank is not a valid Int32”。

但是我该怎么做呢?如何使用可为空的属性和绑定?

提前致谢!

【问题讨论】:

    标签: asp.net data-binding nullable


    【解决方案1】:

    好吧,我找到了一个解决方案,其中包括一个 FormView,但是您没有指定它是否适合您的场景。

    无论如何,在我的情况下,DataBound-ed 实体是我自己的 dto(并不重要),诀窍是当您更新 formview 时,您必须基本上附加预数据绑定事件并重新将空字符串写入空值,以便框架可以将值属性注入到构造的对象中:

    protected void myFormView_Updating(object sender, FormViewUpdateEventArgs e)
    {
         if (string.Empty.Equals(e.NewValues["MyProperty"]))
             e.NewValues["MyProperty"] = null;
    }
    

    插入时类似

    protected void myFormView_Inserting(object sender, FormViewInsertEventArgs e)
    {
         if (string.Empty.Equals(e.Values["MyProperty"]))
             e.Values["MyProperty"] = null;
    }
    

    让这个真正有趣的是,错误消息(不是有效的 Int32)实际上是错误的,它应该写(不是有效的 Nullable),但 nullables 应该是第一个他们不会是阶级公民吗?

    【讨论】:

      【解决方案2】:

      我开始相信绑定可为空的值属性是不可能的。到现在为止,我只能看到添加一个额外的辅助属性来绑定一个可为空的类型的解决方法:

      public int? MyProperty { get; set; }
      
      public string MyBindableProperty
      {
          get
          {
              if (MyProperty.HasValue)
                  return string.Format("{0}", MyProperty);
              else
                  return string.Empty;
          }
      
          set
          {
              if (string.IsNullOrEmpty(value))
                  MyProperty = null;
              else
                  MyProperty = int.Parse(value);
                  // value should be validated before to be an int
          }
      }
      

      然后将helper属性绑定到TextBox而不是原来的:

      <asp:TextBox ID="MyTextBox" runat="server"
          Text='<%# Bind("MyBindableProperty") %>' />
      

      我很高兴看到另一个解决方案。

      【讨论】:

      • 这在数据源为EntityDataSourceFormView 中不起作用——我只是得到DataBinding: 'System.Web.UI.WebControls.EntityDataSourceWrapper' does not contain a property with the name 'MyBindableProperty'.
      【解决方案3】:
      <asp:TextBox ID="MyTextBox" runat="server" 
      
      Text='<%# Bind("MyProperty").HasValue ? Bind("MyProperty") : "" %>' />
      

      您可以使用 HasValue 来确定可空类型是否为空,然后设置 Text 属性。

      【讨论】:

      • 感谢您的回复,耐力赛。但这根本不起作用,甚至无法编译。它可以与 Eval 一起使用(至少在将 Eval 的 return 转换为 int 之后?)但 Bind 是另一回事。
      猜你喜欢
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多