views:

768

answers:

3

I get this error:

System.Reflection.TargetException: Object does not match target type.

when trying to bind a List<IEvent> where an IEvent can be an appointment, a birthday, or a few other calendar related event types.

+2  A: 

ChanChan, GridView does not support binding to a collection of interfaces, Try redisigning your application to ensure binding only to a collection of concreate classes. The only workaround for this is to use base class (in your case Event) and bind to a collection of events.

        public  class Event
        {
            public  DateTime StartDate { get; set; }
        }
        public class Birthday : Event
        {       

            public DateTime? EndDate { get; set; }
        } 
        public class Appointment : Event
        {       

            public string Place { get; set; }
        }
        public class EventCollection : Collection<Event>
        {
            public static EventCollection GetEvents()
            {
                var events = new EventCollection();
                events.Add(new Birthday
                {
                     EndDate = DateTime.Now.AddDays(1),
                     StartDate = DateTime.Now
                });
                events.Add(new Appointment
                {
                    Place = "Gallery",
                    StartDate = DateTime.Now
                });
                return events;
             }
         }

Please note that inheritance from base classes creates 'is a' relation, but inheriting from interfaces creates 'can do' relation. In other words, IMO, implementing IEvent would be a bad design, since Birthday 'is a' Event. I would inherit from base class here.

Hope this helps, Valve.

Valentin Vasiliev
A: 

This cannot be done, don't use a gridview if you need this functionality, is the only way I can get around it.

DevelopingChris
This can be done, there are several workarounds : use inheritance and not Interfaces, use providers, use custom BoundFields (http://iridescence.no/post/FixingBoundFieldSupportforCompositeObjects.aspx)...
Julien N
+1  A: 

It's a little bit of a pain to have to do it this way, but it is possible to bind a list of multiple types to a GridView - you just have to implement a TypeDescriptionProvider for your base type.

More details in this article: Polymorphic Databinding Solutions

bcwood