Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a nullable int to an asp:TextBox

I have a property int? MyProperty as a member in my datasource (ObjectDataSource). Can I bind this to a TextBox, like

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

Basically I want to get a null value displayed as blank "" in the TextBox, and a number as a number. If the TextBox is blank MyProperty shall be set to null. If the TextBox has a number in it, MyProperty should be set to this number.

If I try it I get an exception: "Blank is not a valid Int32".

But how can I do that? How to work with nullable properties and Bind?

Thanks in advance!

like image 334
Slauma Avatar asked Mar 25 '10 22:03

Slauma


1 Answers

Well i've found a solution, which includes a FormView however and you don't specify if that fits your scenario.

Anyhow, in my case the DataBound-ed entity is a dto of my own (not that it should matter) and the trick is that when you update the formview you have to essentially attach on the pre-databound event and re-write the empty string as a null value so that the framework can property inject the value to the constructed object:

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

and similarly on insert

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

what makes this really fun is the fact that the error message ( is not a valid Int32) is actually wrong and it should write ( is not a valid Nullable) but then nullables would have been first class citizens wouldn't they?

like image 154
Jaguar Avatar answered Sep 29 '22 06:09

Jaguar