While I have been working on a project I was asked about hosting user controls within a web part. I talked about using the SmartPart and also writing a custom host web part. As I have been asked this a few times now I thought it useful to document a simple process to getting a user control to run within a web part. Firstly let's create a new user control within Visual Studio 2005. Open up Visual Studio and create a new project based on the ASP.NET Web Application.
Once the project has been created add a new item and add a user control.
The user control will be very simple, for this one it has a textbox and a button.
Textbox = txtValue
Button = btnPressMe
The source for the user control should then look as shown below:
So now we have our control let's add some code so when the button is pressed is populates the textbox.
As you can see it is nice and simple code. So now we need to compile the code which will produce a "DLL" and also "ASCX" control with its accompanying code file. These files now need to be copied into the following folders that are found in the Web Application IIS folder. For this example mine is:
C:\InetPub\wwwroot_INTRANET
The following files need to be copied into the locations shown above:
Now that our files are ready we need to add the host web part. For this demonstration I have am going to use the user control web part that was installed onto my MOSS2007 server when I installed the Atidan SharePoint Explorer which is free. To access this web part you will need to open up the web part gallery.
Select the "ReflectionIT.SharePoint.WebParts.UserControlContainer" web part and then select the "Populate Gallery" button. Once the web part is added it should then be available from the web part screen when adding web parts.
Once added you need to edit the web part and change a property value.
You will notice that the "User Control" property is set the following location:
~\usercontrols\
This is the location we added the files to earlier on. No we need to change the link above to the following:
Once this is saved the web part should then render the user control as shown below:
When the button is clicked it should then look as below:
This was a very simple example and shows how to use a 3rd Party host web part to use user controls. In the next post we will look at creating a little more interaction between user controls and also look at creating our own host control.