Textbox Bound to Property of Business Object - String Set to Nothing

LerkHern

Member
Joined
Jul 7, 2005
Messages
7
Location
Chicago
Programming Experience
3-5
I've got a property on a custom business object bound to a textbox.

In my binding, I've set the nullValue = String.Empty

When I type in the textbox, then erase the text in my textbox and try to leave... it tries to set the string property in my business object to "Nothing"

This is a problem for me because I've got code that checks the length of the string for validation purposes. I know I could handle it at the business object level but I am completely perplexed by the fact that it's trying to set the string to "Nothing"

PS. I've got a Parse Event on the binding, and at that point when I check e.Value it evaluates to "" (String.Empty) but as soon as it leaves that event and tries to set the property the value is Nothing instead of String.Empty

Binding Code:

VB.NET:
Dim binding As New Binding("Text", MyObject, "MyStringProperty", True, DataSourceUpdateMode.OnValidation, String.Empty, Nothing)

AddHandler binding.Parse, AddressOf oBinding_Parse

binding.ControlUpdateMode = ControlUpdateMode.OnPropertyChanged
Control.DataBindings.Add(binding)

Parse Event:
(e.Value evaluates to "" so it doesn't even hit the line that sets it to "")

VB.NET:
Private Sub oBinding_Parse(ByVal sender As Object, ByVal e As System.Windows.Forms.ConvertEventArgs)

        If e.DesiredType Is GetType(String) Then
            If e.Value Is Nothing Then
                e.Value = ""
            End If
        End If

End Sub

Set For my property (it errors on the value.Length part)
I know I could alter this code to handle nothing but I'd rather not patch the business object to handle the strange databinding problem

VB.NET:
Set(ByVal value As String)
	If value.Length > 10 Then
		Throw New Exception("Invalid Length")
	End If
	mMyStringProperty = value
End Set
 
It happens because you have set FormattingEnabled True, if you check the Format event after deleting the content the Value is Nothing. No need to format from String property to String property.
 
Ah, Thank you very much! I googled for like 2 days trying to figure this out and in a couple hours you reply with an answer!

So... I do have a reason why I'm using the formatting - There's a little more to each chunk of code, I only posted the important parts.

The reason I've got formatting on is for other TextBoxes that have a Currency string format, but I suppose that I can turn it off for the Textboxes that do not have any special formatting.

I have a feeling I won't have any problems with the currency boxes because they're bound to properties with a numeric datatype so I think I'll be in the clear.

Thanks again JohnH!!!
 
Back
Top