In our last post we looked hosting a simple user control using a 3rd Party host web part. In this post let's look at creating our own host control. To do this we first need a new class project created using Visual Studio. Once created remove the existing class file and a new one, for this demonstration I have called it "UserControlHostWP.cs". The code for the class should look as shown below:
Before we start we will need to make sure we modify the declarations so that they include the reference for "Web Part".
The public class will also need to be changed so it inherits from the "Web Part" class. The code should be changed to the following:
So now we have our base class let's start adding the code needed to host the user control. Firstly we need to add a couple of properties, one that will create the textbox that is completed from the web part properties, the other being the instance of the User Control that will be used within the code.
To add the path property, change the code to the following:
To create the instance of the user control, modify the code further by adding the following:
So now we have a web part property exposed and the user control instance, now we simply need to render the user control within the web part. This is done by using the following code:
This code will take the path that was specified in the tool pane of the web part and render it accordingly. Notice how we are adding the user control as a control within the web part and then rendering them together as one item.
Now we have the web part created we can simply upload this into SharePoint and add this to the page as shown below:
Select the Web Part from the Web Part Picker
Populate the user control property with the correct location, is this example I am using "~/usercontrols/" you could use "~/controltemplates" if you wish, or a custom folder within the site structure.
The control should render as shown below, if you get the following error message:
This is caused by there being no error handling for the web part property being empty.
Notice how the button functions as before
This is a very powerful way of rendering controls, as the user design surface for web parts is really non-existent, user controls become a more viable solution. In the next post we will look at creating host controls and user controls that can connect to each other and pass values between themselves.
Just want to say a big thank you to Fons Sonnemans for this article:
http://www.reflectionit.nl/SmartPart.aspx
And also Sean Skinner for his code sample that was the basis for the code above:
http://www.binarywave.com/blogs/sskinner/Lists/Posts/Post.aspx?ID=3