none
IList<T> and BindingSource problem RRS feed

  • Question

  • I've noticed a odd problem when using a class that implements IList<T> with a BindingSource. I've managed to reproduce the problem with some simple classes. I have a class called BaseClass and several classes that derive from BaseClass called DerivedClass1, DerivedClass2 and DerivedClass3.

    Now I create a class to act as a collection of BaseClass objects called BaseClassCollection. BaseClassCollection implements IList<T> and basically just wraps a List<BaseClass> at this point. At this point everything works fine and I can populate the BaseClassCollection with objects of type DerivedClass1, DerivedClass2 and DerivedClass3 to create a heterogenous collection.

    Now the problem comes when I try and use BaseClassCollection as a DataSource for a BindingSource. I create a form with a ListBox control with it's DataSource set to a BindingSource. I then set my BindingSource to bind to an empty BaseClassCollection. Then I add three buttons that will add either a DerivedClass1, DerivedClass2 or a DerivedClass3 object to the collection and refreshes the BindingSource. If I add several objects of the same type then I have no problem, but as soon as I try to add a object of a different class I get an exception:

     

    The value "BindingTest.Derived2" is not of type "BindingTest.Derived1" and cannot be used in this generic collection.
    Parameter name: value

     

    It seems that when you set the DataSource of the BindingSource to an IList<T> it looks at the first item in the list (let's say it's a DerivedClass1) and assumes that the list is a DerivedClass1 list and won't let you add anything that isn't a DerivedClass1. What it should do is recognize that it's an IList<BaseClass> and assume we have a list of BaseClass and thus allow the addition of any class derived from BaseClass. Oddly enough, if I make my BaseClassCollection inherit from List<BaseClass> instead or implementing IList<BaseClass> then it works as expected, but I lose the ability to control the implemenation of the list.

    Does anybody know what is happening here? How do I make the BindingSource realize that it's dealling with a collection of BaseClass?

    Friday, June 8, 2007 1:41 PM

Answers

  • I noticed that List<T> implements IList<T> and IList. So I added IList to my class and it now seems to work. Does anybody know why?
    Saturday, June 9, 2007 1:28 AM