ASP.NET Convert Invalid String to Null
-
09-06-2019 - |
Question
In my application I have TextBox
in a FormView
bound to a LinqDataSource
like so:
<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);
}
This is inside an UpdatePanel
so any change to the field is immediately persisted. Also, the value of MyValue
is decimal?
. This works fine unless I enter any string which cannot be converted to decimal into the field. In that case, the UpdateItem
call throws:
LinqDataSourceValidationException - Failed to set one or more properties on type MyType. asdf is not a valid value for Decimal.
I understand the problem, ASP.NET does not know how to convert from 'asdf' to decimal?. What I would like it to do is convert all these invalid values to null. What is the best way to do this?
Solution
I think you should handle the Updating event of the LinqDataSource on your page. Do your check for invalid strings (use a TryParse method or something) and then continue with the base class update.
(Edit: My intuition lines up with what's recommended here)
OTHER TIPS
Not familiar with ASP, but in .net, couldn't you just do something along the lines of
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);
}