Wrap UserControl into SharePoint WebPart


 

Creating a webpart now is easier with VS 2008. But the difficulty is, there is no designer for the webpart so every time we would know only when we deploy. Its time consuming and also difficult to visualize it at runtime. So the cool feature of webpart is we can directly load a user control to it. Although some of the third party tool (http://www.codeplex.com/smartpart) allows to load the user control directly in the WebPart, i have mentioned a code based approach below to load the user control. Most the developers might be aware of it, may be my blog will help a novice sharepoint developer.

Below are the steps to be done to create a webpart which loads the user control. I am using the latest Visual Studio 2008 extensions for SharePoint v1.3.

Creating Webpart Project

Create a new project, select sharepoint option from the list and select WebPart project from the right pane. Enter HelloWorld for the project name

  image

Select the full Trust option.

clip_image004

Rename the folder to HelloWorld, which will automatically rename all the webpart component. Only the latest VS extension will do the rename automatically.

clip_image006

clip_image008

Creating a ASP.NET User Control

Right click on the Helloworld solution and add New Project and Select ASP.NET Web Project and name it to HelloWorldControl

clip_image010

Delete the default.aspx file and Add New Item and select Web User Control from the list and Name it to HelloWorldUC.ascx

clip_image012

Remove the CodeBehind attribute in the HelloWorldUC.ascx.

Add a reference to Microsoft.SharePoint dll in the project. To do it Right Click on the project Add reference and Select Windows SharePoint Services.

Navigate to the Design view for the HelloWorldUC.ascx and from the toolbox add the Panel to the Control and change the ID from the Property window to HelloPanel.

In the HelloworldUC.ascx.vb add the following code to show the username. Also declare a property Web to get the SPweb context to the user control

Private myWeb As SPWeb

Public Property Web() As SPWeb
        Get
            Return myWeb
        End Get
        Set(ByVal value As SPWeb)
            myWeb = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Dim currentUser As String = Me.Web.CurrentUser.Name
            HelloPanel.Controls.Add(New LiteralControl(String.Format("Hello {0}! ", currentUser)))
        Catch ex As Exception
            HelloPanel.Controls.Add(New LiteralControl(String.Format("Error {0}! ", ex.Message)))
        End Try
    End Sub

Build the ASP.NET Control(HelloWorldControl) project to get the HelloWorldControl Assembly. Before building make sure you enable signing from the Project Settings to sign the Assembly. Failing to sign might get error cannot emit Assembly.

clip_image014

Adding Folder and Control to Webpart Project

Now go to the WebPart Project right click and Add New Item and select SharePoint and Select Templates. This will Add a Templates Folder and Template.txt file to the folder. Delete the txt file from the project. Right click on the Templates folder and Add New Folder and rename the folder to ControlTemplates. Right click again on the ControlTemplates folder and Add Folder and name it to Helloworld (to deploy project specific files).

clip_image016

Now right on the HelloWorld folder Add Existing Item and select the HelloWorldUC.ascx file and from the bottom select the Add As Link. If the code behind file (HelloWorldUC.ascx.vb) is added remove it. Because might get error while compiling.

clip_image018

Once everything is done the Project structure will look like the below image

image

Now add the reference to the HelloWorldControl.dll in the WebPart Project. In the CreateChildControls add the code pasted below

Protected Overrides Sub CreateChildControls()
            MyBase.CreateChildControls()

            Try
                ‘ Loads a user control
                Dim myUserControl As HelloWorldControl.HelloWorldUC = CType(Page.LoadControl("~/_controltemplates/HelloWorld/HelloWorldUC.ascx"), HelloWorldControl.HelloWorldUC)
                myUserControl.Web = SPContext.Current.Web
                ‘ Adds it to the controls collection of the Web Part
                Me.Controls.Add(myUserControl)

            Catch ex As Exception
                Me.Controls.Add(New LiteralControl("<br />An unexpected error occurred loading Web Part. " + ex.Message))
            End Try
        End Sub

Build the solution and it should build without error.

Deploying the Solution to SharePoint

To deploy the webpart go to Webpart Project right click on the project and Properties. In the Properties select the debug and enter the SharePoint URL to be deployed.

Now copy the Helloworld.dll and the Helloworldcontrol.dll to the C:\inetpub\wwwroot\wss\VirtualDirectories\8080\bin coz in my case the site is in 8080 port. The directory will change depends on the port selected

Now Right Click on the WebPart project (HelloWorld) and click on deploy solution. This will deploy the webpart to the site and Adds it to the webpart gallery.

image

To see the webpart gallery Navigate to SiteActions->Site Settings, Under Gallery section select the Web part. Now in the list you should be able to see the HelloWorld.webpart. Click on the webpart will show the preview. It also shows any error occurs

image

The WebPart is now successfully deployed to the Server.

3 thoughts on “Wrap UserControl into SharePoint WebPart

  1. Rachel

    Hi!!

    thanks about the post , it’s very clear.
    I did all the steps but i get error :”An unexpected error occurred loading Web Part. The file ‘/_ControlTemplates/PortalDev/RadMenu.ascx’ does not exist”.
    but this file is exist so what the problem?
    if you have a answer it will be very helpful.
    thank and good day

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s