Fixing lost data in a data bound control that causes an exception

Vusual Basic .NET 2008 is wonderful. It makes working with databases a breeze (sort of…) Using datasets and databindings, you can create a data driven application with very little hand-written code.

Recently, a user of one of my apps encountered an unhandled error (yeah I know. Whoops.) “The value violates the MaxLength limit of this column” and was allowed to continue or quit. He chose continue, clicked save again, and even though it appeared to save, nothing actually saved.

The exception happened when bindingsource.EndEdit() was called on the table containing the undersized field. Debugging showed that after the error occurs, the underlying datarow is reverted to the pre-modified state.

It doesn’t make sense – it might be simple to fix, it might be (probably is) my fault, but nonetheless the internet failed me in finding a solution, so I made one up.

The values that the user had spent hours working on are still in the controls, but the underlying binding source has changed. If we push the changes from all the controls back out to the datarow, saving again will create the error again – as it should.

You push the changes back by calling the WriteValue() function on the data binding for a data bound control ( dataTextBox.DataBindings(0).WriteValue() ). Because I didn’t want to hard code anything, I looped through all the controls on the form.

Here is the semi-pseudocode I cludged together to get the app working. Please let me know if there is a better way.

Sub commitChanges()
  Try
    myBindingSource.EndEdit

  Catch ex as Exception
    msgbox(ex.message)
    updateAllBindings()
  End try
End Sub

Sub updateAllBindings()
  For Each contr As Control In Me.Controls
    For Each cbind as Binding in contr.DataBindings
      cbind.WriteValue()
    Next cbind
  Next contr
End Sub

Note: if you use any containers (tabs, panels, flowlayout) you will probably have to create a separate loop for each subcontainer.

Ideally, the app would warn the user when control is validated, but I guess dataset field restrictions are not pushed to the control (and I’m too lazy to hand update each and every one).

Once again, I find it hard to believe I’m the first person to have this problem…

Leave a Reply

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