I am having a problem implementing databinding in my .NET 2.0 app. I have a number of controls on a user control (the user control's autovalidate property is set to 'disabled'. I fill in the form fields, and try to save the data. The application calls ValidateChildren() on the user control, and my Validating event handlers fire as expected. But somewhere during this process (while the validating event handlers are running) one of my textboxes loses its value (it's reset to empty string). So, by the time its own validating event handler runs, it fails because this is a required field.
The really odd thing is that if I then try to save this again, everything runs as expected.
This is a sample of the code that adds the databindings to my controls:
private void CreateControlDataBindings(customBusinessObject b)
{
this._personBindingSource = new BindingSource();
this._personBindingSource.DataSource = b;
this.cboTitles.DataBindings.Clear();
this.cboTitles.DataBindings.Add(new Binding("SelectedValue", this._personBindingSource, "Title", true, DataSourceUpdateMode.OnValidation));
this.txtForename.DataBindings.Clear();
this.txtForename.DataBindings.Add(new Binding("Text", this._personBindingSource, "Forename", true, DataSourceUpdateMode.OnValidation));
//this is thw one which loses its value
this.txtSurname.DataBindings.Clear();
this.txtSurname.DataBindings.Add(new Binding("Text", this._personBindingSource, "Surname", true, DataSourceUpdateMode.OnValidation));
}
And these are my validating event handlers:
private void cboTitles_Validating(object sender, CancelEventArgs e)
{
e.Cancel = !this._validationManager.ValidateItemSelected(this.cboTitles, "A title is required.");
}
private void txtForename_Validating(object sender, CancelEventArgs e)
{
e.Cancel = !this._validationManager.ValidateNullOrEmpty(this.txtForename, "A forename is required.");
}
private void txtSurname_Validating(object sender, CancelEventArgs e)
{
e.Cancel = !this._validationManager.ValidateNullOrEmpty(this.txtSurname, "A surname is required.");
}
The first two both run as expected (i.e. they don't cancel the event), then somewhere between the 2nd and 3rd handler, the txtSurname text value is reset. I notice a slight pause in the application before this happens- almost as if the application is trying to push some data back to the datasource, and failing for some reason.
The business object I am working with contains both a Forename and Surname property, so the problem is not that it can't write the value back to the property I have bound the control to.
If anyone has any suggestions for how to make this work, I would extremely pleased to hear them, as informing the prospective users that they will have to click the save button twice would not go down terribly well.