【问题标题】:Is it possible to pass a format string to Bind() from code behind?是否可以从后面的代码将格式字符串传递给 Bind() ?
【发布时间】:2014-08-04 05:17:55
【问题描述】:
  • 网络表单,.NET 4.51

使用标准数据绑定如下:

<asp:TextBox TabIndex="254" Text='<%# Bind("ClientTwoDateOfBirth", "{0:yyyy-MM-dd}") %>'  ID="txtClientTwoDob" runat="server"></asp:TextBox>

是否可以调用后面的代码动态获取格式化字符串?类似于以下内容(不起作用):

<asp:TextBox TabIndex="254" Text='<%# Bind("ClientTwoDateOfBirth", "{" + GetFormatStringFromCodeBehind() + "}") %>'  ID="txtClientTwoDob" runat="server"></asp:TextBox>

谁能指出我正确的方向?

【问题讨论】:

  • 你能提供我隐藏功能代码的代码吗..我无法确切了解究竟是什么
  • 下面的链接会帮助你stackoverflow.com/questions/12754016/…
  • @Balaji 该示例仅适用于通过 Eval() 进行的一种方式绑定。我想使用 Bind() 维护双向数据绑定,但确定格式字符串(动态第二个参数)

标签: c# asp.net webforms


【解决方案1】:

您可以从后面的代码中获取文本框所需的 FormatString

aspx

    <asp:TextBox ID="TextBox1" runat="server" Text='<%# GetFormatStringFromCodeBehind(    Eval("columnName")) %>'></asp:TextBox>

aspx.cs

      public string GetFormatStringFromCodeBehind(object obj)
    {
        return Convert.ToDateTime(obj).ToString("dd/MM/yyy");
    }

你应该使用 Eval 而不是 Bind

【讨论】:

  • 我还是想通过 Bind() 维护双向数据绑定
【解决方案2】:

Bind() 表达式中不可能有比普通字符串更复杂的东西。甚至还有一个关于此的错误报告(几乎与您的问题相同)-Data Binding with "Bind" and Formatting Problem (ASP.Net) 和官方回复:

Microsoft 于 2009 年 1 月 22 日上午 7:23 发布

您看到的行为是设计使然。 Bind 表达式是一个 ASP.NET 代码生成的非常专业的部分,它有一个 格式参数必须是文字的限制,您可以采样 失败,因为格式字符串是一个函数。你可以阅读 更多关于 Bind 的细节在这里: http://weblogs.asp.net/leftslipper/archive/2007/06/29/how-asp-net-databinding-deals-with-eval-and-bind-statements.aspx.

【讨论】:

    【解决方案3】:

    我通常做的是使用 DataBinder.Eval 在 PreRender 获取 TextBox 的值并设置它。您可以添加一个条件来检查您是否处于编辑模式。

    参见下面的示例代码:

    在您的 .aspx 中:

    <asp:TextBox OnPreRender="txtClientTwoDob_PreRender" TabIndex="254" Text='<%# Bind("ClientTwoDateOfBirth") %>'  ID="txtClientTwoDob" runat="server"></asp:TextBox>
    

    在你的代码后面:

        protected void txtClientTwoDob_PreRender(object sender, EventArgs e)
        {
            TextBox txtClientTwoDob = (TextBox)sender;
            //You can check also if you are in edit mode or not before performing this
            txtClientTwoDob.Text = DataBinder.Eval(txtClientTwoDob, "Text", "{0:yyyy-MM-dd}");
        }
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      相关资源
      最近更新 更多