I have recently started working on my first MOSS project and came up with a very common scenario of wanting to use UserControls into WebParts simply because of the great Designer support for UserControls in Visual Studio. (Usercontrols vs WebParts)
Also I wanted my WebParts to just act like a shell and provide me the build in features of serializing, storing, and retrieving the site customization and member personalization data without being worried about rendering of the actual UI controls.
So, I created a WebPart which can host any Usercontrol dynamically and also expose the configured properties of the usercontrol onto a custom editor. It sounds like re-creating your own SmartPart but I thought to give it a try to understand how things work.
Ok, here is an overview of some of the important bits that I did :
- Created a property on the WebPart for storing the path of the Usercontrol and loaded the usercontrol dynamically using Page.LoadControl function in the CreateChildControls method of the WebPart.
- Created a custom editor part by inheriting EditorPart and in the CreateChildControls method extracted all the editable properties of the UserControl currenly loaded on the WebPart using TypeDescriptor.GetProperties()method.
- Then I added a TextBox control for each of these properties on the custom editor. ( We can further add a smart selection of controls based on the types of the properties eg: Checkbox for Boolean property, DropDownList for List and RadioButtons for Enums)
Now the most important thing was to make sure that the values typed in from the custom editor part should be passed on to the actual UserControl hosted in the WebPart.
- So I created an ArrayList of controls added for properties, on the custom editor part and a Hashtable of propertynames, on the WebPart. On the ApplyChanges()method of the custom editor part I looped through all controls ArrayList and assigned the value of the control to the Hashtable in the WebPart with the key as the property name.
- Then it was just a matter of looping through the Hashtable and setting the values back to the UserControl in the CreateChildControls method of the WebPart.
I have attached the code below along with a sample ASCX file to use. I kept the ascx file in the IIS webapplication folder under a sub folder named “UserControls”.
eg: C:\Inetpub\wwwroot\wss\VirtualDirectories\[WebAppDirector]\UserControls



