Question

I am binding a data source to a Windows Forms TextBox, and the source has to validate with each keypress to provide timely user feedback (in the form of related controls being enabled/disabled). Therefore I am binding with DataSourceUpdateMode::OnPropertyChanged. Unfortunately this is causing the textbox to reset the cursor to the left of the field with every keystroke, causing user input to be reversed. Using DataSourceUpdateMode::OnValidation eliminates the cursor problem, but then of course the data source isn't updated until focus leaves the TextBox, and that is not acceptable in this case (I have an "Apply" button that is gray until a value changes).

This thread describes the problem, but only for a RichTextBox, and claims that the problem doesn't exist for a regular TextBox. I am having the problem with a regular TextBox.

Has anyone seen this issue and found a way to work around it and still use a Binding object?

EDIT: Testing has revealed that the Click event for a button on the form fires before validation, meaning that if a user clicks in a text field to change a value, then clicks directly on "Apply," the entered value is not propagated to the data source in time to respond to the click. In other words, the usefulness OnValidate with a text box is significantly reduced for my application.

Was it helpful?

Solution

Turns out turning on string formatting for the binding fixes the caret position problem.

What was:

textbox->DataBindings->Add("Text", model_object, "MyProperty", false, 
    DataSourceUpdateMode::OnPropertyChanged);

becomes:

textbox->DataBindings->Add("Text", model_object, "MyProperty", true, 
    DataSourceUpdateMode::OnPropertyChanged);

and like magic, the caret stops repositioning itself. If anyone can comment and explain why this makes sense, please do!

This MSDN forum post provided the hint to try turning on string formatting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top