Wednesday, March 23, 2011

Databinding in windows forms on an object graph with possible null properties?

If I have an object graph like this:

class Company { public Address MainAddress {...} }

class Address { public string City { ... } }

Company c = new Company(); c.MainAddress = new Address(); c.MainAddress.City = "Stockholm";

and databind to a control using: textBox1.DataBinding.Add( "Text", c, "MainAddress.City" );

Everything is fine, but If I bind to: Company c2 = new Company();

c2 using the same syntax it crashes since the MainAddress property is null. I wonder if there is a custom Binding class that can set up listeners for all the possible paths here and bind to the actual object dynamically when/if I sometime later in the application set the MainAddress property.

From stackoverflow
  • You should change the getter of the property MainAddress to do this null check, and return an "empty MainAddress"

0 comments:

Post a Comment