ASP.NET将无效字符串转换为Null

时间:2020-03-05 18:52:50  来源:igfitidea点击:

在我的应用程序中,我的FormView中有一个TextBox绑定到一个LinqDataSource,如下所示:

<asp:TextBox ID="MyTextBox" runat="server" 
             Text='<%# Bind("MyValue") %>' AutoPostBack="True" 
             ontextchanged="MyTextBox_TextChanged" />

protected void MyTextBox_TextChanged(object sender, EventArgs e)
{
    MyFormView.UpdateItem(false);
}

它位于UpdatePanel内部,因此对字段的任何更改都会立即保留。另外," MyValue"的值是" decimal?"。除非我在该字段中输入无法转换为十进制的任何字符串,否则此方法效果很好。在这种情况下,UpdateItem调用将引发:

LinqDataSourceValidationException -
  Failed to set one or more properties on type MyType.  asdf is not a valid value for Decimal.

我了解问题,ASP.NET不知道如何从" asdf"转换为十进制?我想要做的是将所有这些无效值都转换为null。做这个的最好方式是什么?

解决方案

回答

我认为我们应该在页面上处理LinqDataSource的Updating事件。检查无效字符串(使用TryParse方法或者其他方法),然后继续进行基类更新。

(编辑:我的直觉与这里建议的一致)

回答

对ASP不熟悉,但是在.net中,我们不能按照以下方式做一些事情吗?

protected void MyTextBox_TextChanged(object sender, EventArgs e)
{ 
    Decimal d = null;
    TextBox tb = sender as TextBox;

    if(!Decimal.TryParse(tb.Text, out d))
    {
            tb.Text = String.Empty;
    }
    MyFormView.UpdateItem(false);
}