Archive for September, 2007

Null Your DataSources!

Sunday, September 23rd, 2007

I’ve recently been working on an application that mimics a Windows Forms designer–essentially, a toolbox, the design surface itself, and a property grid. One requirement we had is that we needed to save the contents of the design surface (the controls, their sizes, and their child controls) to an XML file, so it could be reloaded at a later point.

The approach a co-worker and I had taken to serialize the data was to write controls and control-specific data in XML and to write serializable objects (business objects that the controls had references to) as binary data. During this process, I had a very painful debugging experience trying to figure out why the BinaryFormatter was trying to serialize a ListBox when I had told it to serialize one of our business objects. The only thing we had done differently before saving was that we had edited a property which showed a dialog which contained a few ListBox objects.

That action was most definitely related to the issue, but we still couldn’t think of why it was trying to serialize the ListBox, especially after the dialog was closed.

After a couple of hours, I was a little astounded at the cause. It turns out that when we set the DataSource property on the ListBoxes in the dialog I mentioned earlier, the WireDataSource() method in the ListControl was called. Since our business entities also implement IComponent (courtesy of .netTiers), the method attaches its DataSourceDisposed method to the Disposed event of the bound object. Thus, when we tried to serialize the object, the link between its Disposed event and the DataSourceDisposed event handler had not been broken, and it had tried to save the containing type of DataSourceDisposed.

The simple fix was to set the DataSource properties on the ListBox to null when the Form closed. Almost a kick in the face after all that. :)