This project is read-only.

SmartPart Collections problem

Nov 27, 2007 at 6:02 PM
Edited Nov 27, 2007 at 6:04 PM
I have 10 or so usercontrols that I load dynamically at run time and add to my main form. These controls contain charts, grids etc.

I added the user controls to the smartpart collection and my everything was fine. When the application launches, it takes one of each user control from the smartparts collection and places them in preset panels on the mainform....and all is well.

The application allows the user to create more panels and add more userControls from a list of the existing controls. looks like once a usercontrol has been added once on initialization/startup, if the user tries to add another copy of that user control to a new panel they created, we get null as the return value when we call to SmartParts.Get method.

Please help.
Nov 28, 2007 at 2:11 PM
Hi Elbino,

This is caused by a subtle behavioral difference between the Items and SmartParts collections. The SmartParts collection is populated automatically during build up. Any user controls decorated with SmartPart will be added to it. There is a filter applied to the SmartParts collection such that items without the SmartPart attribute won't be visible once inside the collection.

The problem is that the filter is not applied when you add an item. It could be argued that this is a bug. It might be nice to have an exception thrown if you attempt to add an item to a ManagedObjectCollection where the item does not pass the filter. Oh, well.

So there's a couple of things you can do to fix this:
  • decorate all your smart parts with the SmartPart attribute. Now when you add them to the SmartParts collection, you will be able to retrieve them afterwards because they will pass the filter.
  • use the Items collection instead.

I'd recommend the latter approach, because the former approach is a bug waiting to happen. If you forget to apply the SmartPart attribute somewhere your code will break and it may not be obvious why. Of course, you could also put some diagnostic code in to ensure this doesn't happen. At the end of the day, it doesn't really matter which collection it is stored in - as long as you can get it back out!