views:

229

answers:

2

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!

+1  A: 
<asp:TextBox ID="MyTextBox" runat="server" 

Text='<%# Bind("MyProperty").HasValue ? Bind("MyProperty") : "" %>' />

You could use HasValue to determine if the nullable type is null, and then set the Text property.

enduro
Thanks for reply, enduro. But this does not work at all and even does not compile. It would work with Eval (at least after casting the return of Eval to int?) but Bind is a whole other story.
Slauma
A: 

I'm starting to believe it's not possible to bind a nullable value property. Til now I only can see the workaround to add an additional helper property to bind a nullable type:

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
    }
}

and then bind the helper property to the TextBox instead of the original:

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

I'd be happy to see another solution.

Slauma