Data-bound TextBox: can’t exit

Posted on

Problem :

I’ve got a text box bound to an object’s property (in fact several text boxes) on a form. This for is an editor for an object. When i’m editing some objects and modify values in the one of the text boxes i can’t exit from the text box (neither by tab nor clicking on another text box). However that’s not always the case – when editing other objects (of the same type) it works fine.

Here’s a code snipet:

txtValue.DataBindings.Add("Text", _SourceObject, "PlannedValue", True, DataSourceUpdateMode.OnPropertyChanged, Nothing, "c")
txtEstPlacements.DataBindings.Add("Text", _SourceObject, "EstimatedPlacementCount")
txtReference.DataBindings.Add("Text", _SourceObject, "Reference")

Any suggestions?

Solution :

Sounds like a data validation issue. Check if the controls on the form have their CausesValidation properties set to true or false.

Also check the AutoValidate property on the form. It is probably set to EnablePreventFocusChange (which is the default).

It may also be the case that the value being supplied in the text box can not be converted to the type of the property it is bound to on the source data object. I believe the Convert class is used for this (though I may be wrong here).

You may want to check out this article on MSDN that covers winforms validation in some detail.

If your Form has AutoValidate==EnablePreventFocusChange, then you’ll end up with the focus stuck in any field that fails validation.

Note that validation is considered to have failed if there is an exception when writing the value into the object.

Try setting a breakpoint at the entry point of the setter of the property that’s bound to the control where the cursor gets stuck. Then, single step to see if an exception is raised.

If the breakpoint never fires, the exception may be occuring within the Databinding framework.

Contrary to popular believe, the databinding framework does log errors and other useful information – it uses support from the System.Diagnostics namespace to do this. I forget the details, but they’re on MSDN – you should be able to view the diagnostics in the messages window of Visual Studio while your application runs. Very useful for troubleshooting issues with Databinding.

In order to fix the validation failure, which is due to the inability of the databinding to set DBNull.Value into the textbox.text, you may add the following line in the Form_Load section:

TextBox1.DataBindings["Text"].NullValue = string.Empty;

for each text box you want to allow empty value to be validated correctly.

See more details on Microsoft Connect.

and on:

Can’t escape empty textbox

Leave a Reply

Your email address will not be published. Required fields are marked *