Here is a DataBinding "bug" that drives you nuts. Your "First
Name" TextBox is bound to your Employee object's "FirstName" property.
You change the TextBox value from "Nancy" to "Sally" and
then click the Save button in the ToolStripMenu at the top of your form.
You later discover that your change
was not saved; the first name is still "Nancy".
You are sure you made that change and
it said "Sally" on screen.
So you change the name again, tab
out of the FirstName TextBox, and
click the Save button. You re-read
the Employee and her first name is "Sally".
What is going on?
The FirstName DataBinding did not
complete when you clicked the ToolStrip's
Save button. The TextBox value, "Sally",
was not passed through to the Employee
object's FirstName property so that
property value still read "Nancy" when
your application tried to save it.
Default DataBinding does not update
the bound data item property until
the control loses focus. The FirstName
TextBox did not lose focus when you
clicked the ToolStrip Save button.
It only lost focus when you tabbed
out of the TextBox, which is why your
second attempt worked.
ToolStrip buttons are different in
this respect from the buttons you drag
onto the Form. When you click a Form
button, the TextBox loses focus, the
button gains focus, the DataBinding
completes, and "Sally" makes
it to the database.
ToolStrip buttons do not gain focus
and the current control does not lose
focus. Therefore, by default, DataBinding
does not complete and the bound data
item property remains unchanged.
Why are ToolStrip buttons different?
Because you might want the button action
to do something other than commit the
TextBox value. The button might make
the selected text bold, it might correct
your spelling, or it might send out
for room service. The .NET designers
did not want to presume too much.
You must add a line of code to your
button handler to ensure that a pending
DataBinding completes. The handler
must tell the Form (or UserControl)
to "validate" itself by calling
its Validate() method. |