Databinding to business objects and exceptions
One cool, and not quite new, feature of Visual Studio 2005 is data binding to your own business objects. Just create a new business object class, add a property, add it to the Data Sources window as an object data source and drag it onto your form. Simple as that and you are good to go.
However as usual there is a gotcha :-(
It throw an exception in a property get or get during the data binding the exception is eaten by the DataBindings object. There are two ways around this, either pass False as the formattingEnabled parameters or add an event handler to the BindingComplete event and check for the Exception property being set.
The first option seems the easiest but isn’t :-( Even if you set the Format type to no formatting in the Formatting and Advanced Binding dialog the formattingEnabled will still be true.
That leaves the second option. To handle the BindingComplete event you need to ass an event handler to all Binding objects on the form. Not difficult once you have a reference to all controls. The following code does just that.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each control As Control In GetAllControls(Me)
For Each binding As Binding In control.DataBindings
AddHandler binding.BindingComplete, AddressOf BindingCompleteHandler
Private Sub BindingCompleteHandler(ByVal sender As Object, ByVal e As BindingCompleteEventArgs)
If e.Exception IsNot Nothing Then
Throw New Exception("Unhandled exception during databinding actions.", e.Exception)
Private Function GetAllControls(ByVal container As Control) As List(Of Control)
Dim result As New List(Of Control)
Dim pos As Integer = 0
Do While pos < result.Count
For Each control As Control In result(pos).Controls
pos += 1
Public Class SomeData
Private _lastName As String = "Maurice de Beijer"
Public Property LastName() As String
Throw New Exception("Get: " + _lastName)
Set(ByVal value As String)
_lastName = value
Maurice de Beijerwww.TheProblemSolver.nl