Properties of type List<T>

Properties of type List<T>

Old forum URL: forums.lhotka.net/forums/t/841.aspx


razorkai posted on Tuesday, August 08, 2006

Just hit on an interesting issue.  We had an object that was generating the old "Object is not valid and cannot be saved" exception.  It turned out that the property causing this was of type List<string>.  We were adding to the property using the Add method of the List but of course this does not make use of the setter in a property and therefore PropertyHasChanged never gets fired and the object remains invalid even though it should be valid.  We had to create a new inherited List<T> class that provides Add & Remove methods that fire an event ListHasChanged.  The BO then subscribes to this event and calls ValidationRules.CheckRules when it gets triggered.  This seemed like a lot of work and I am wondering if there is a better or preferable approach to the problem?

Would appreciate any feedback.

ajj3085 replied on Tuesday, August 08, 2006

Are there any rules which each string must meet?  Does the list of strings have to contain at least one item?

If so, you should probably create a BO, who's only property is the string value, and a collection based on BLB which enforces the 'must have one item' rule.  That would fit in better when the framework.

Of course that's about the same effort as what you've done already.  If you don't want to subscribe to the lists events, couldn't you override IsValid in the BO, which checks the number / members of the list?  Of course this may indicate you DO need to build out a few more classes as described above.

HTH
Andy

razorkai replied on Tuesday, August 08, 2006

Hi Andy

There are acually three List<T> properties and we have a custom rule saying that the object is not valid if none of the three properties contains any strings.  A BLB object does not feel right because the list is so simple - it has no key info or any fields other then the one simple string.  The IsValid override is an interesting thought, but I am not sure if it is better than our approach.

Thanks.

RockfordLhotka replied on Tuesday, August 08, 2006

Can you use BindingList<T> instead of List<T>? At least that way your list would automatically implement normal binding behavior and the ListChanged event.

Copyright (c) Marimer LLC