CodePrairie .NET

South Dakota .NET User Group


Combobox databinding with Null Values in WinForms 2.0

I've been digging into the databinding features of winforms 2.0. One of the main things I've come to learn is that you do not adapt databinding to your object model, you adapt your object model to databinding /sigh. Oh well...the combo box for me has been a source of much frustration, as it seems to be for many people.

Take this example, say you have an Address object that may or may not have a street assigned to it. On the dataside this means I have an address row with a nullable column for StreetID. So essentially address looks something like

public class Address {
    private Street _street;

    public Street Street {
      get { return _street; }
      set { _street = value; }

Fairly straight forward, and in this class _street may or may not be null. Now suppose in your interface you have a combo box with a list of valid streets. You would most likely bind this combo box with Datasource = BindingList DisplayMember = StreetName and ValueMember = StreetID. You might also be tempted to set the SelectedValue member, but I have had very little luck doing that when binding to objects. Instead you would bind your SelectedItem property to your AddressBindingSource.Street property. Doing it this way databinding will work as expected (you did override Object.Equals   in your Street class right?) except for when Address.Street is null, in that case the first item in the combo box will be selected...not what you want to happen.

So my solution to this problem...a new type of list like this:

class NullSafeBindingList : BindingList where T : new() {
      public NullSafeBindingList(IList list, string keyPropertyName, string displayPropertyName) : base
(list) {
           T nullObj = new
          Type t = typeof
idProp = t.GetProperty(keyPropertyName);
dispProp = t.GetProperty(displayPropertyName);
         idProp.SetValue(nullObj, -1, null
        dispProp.SetValue(nullObj, "", null

So far, this seems to work well. You do have to make sure your Address class can handle (ignore) Streets that have an ID of -1 though.
I only just came up with this today, so I haven't done a lot of testing in the wild with it yet, but I'd love any feedback or comments you might have...good approach, bad approach, did I eat paintchips as a kid well as how you may have solved this problem yourself.

Happy Coding

Published Sep 29 2005, 02:25 PM by chrisortman
Filed under: ,


No Comments

Leave a Comment

Powered by Community Server (Commercial Edition), by Telligent Systems