Home > SharePoint Development > Wrap a User Control inside a Web Part using WSPBuilder

Wrap a User Control inside a Web Part using WSPBuilder

This post will describe how to wrap an ASP.NET User Control in a Web Part for deployment to SharePoint using WSPBuilder. Sharp-eyed readers will notice the similarity with the SharePoint Guidance package article How to: Wrap a User Control Inside of a Web Part for SharePoint which is intential only in an attempt to provide a useful comparison between the different tools, VSeWSS and WSPBuilder.

Creating the Web Part

This procedure demonstrates how to create an ASP.NET Web Part to wrap the user control.

To create the ASP.NET Web Part

  1. In Visual Studio, point to New on the File menu, and then click Project.
  2. In the Project types pane, click WSPBuilder. In the Templates pane, click WSPBuilder Project. In the Name box, type MyWebPart, and then click OK.
  3. Right-click the MyWebPart project, point to Add, and then click New Item…
  4. In the Categories pane, click WSPBuilder. In the Templates pane, click Web Part Feature. In the Name box, type MyWebPart, and then click OK.
  5. In the Feature Settings dialog, type My Web Part for the Title, A web part built using WSPBuilder for the Description and set the Scope to be Web. Click OK.
  6. Open the elements.xml file and edit the values for the Group and QuickAddGroups properties. The following code shows the corrected values:
  7. <Property Name="Group" Value="My Group"></Property>
    <Property Name="QuickAddGroups" Value="My Group" />
    
  8. Right-click on the MyWebPart soluction, then select Build Solution. Note the PublicKeyToken for the compiled assembly.
  9. Optional: Add the following property to the Properties block in the MyWebPart.webpart file to prevent users from closing the web part once it is on a page:
  10. <property name="AllowClose" type="boolean">False</property>

Adding ASP.NET Project Types to the WSPBuilder Project

This procedure demonstrates how to add the ASP.NET web application templates to a WSPBuilder project. This is required to permit the use of the ASP.NET User Control within the WSPBuilder project.

To add the ASP.NET templates

  1. In Visual Studio, right-click on the MyWebPart project and select Unload Project.
  2. Right-click on the MyWebPart project again and select Edit MyWebPart.csproj. Locate the ProjectTypeGuids element and add the ASP.NET web application project type guid {349C5851-65DF-11DA-9384-00065B846F21}. The following code shows the corrected element:
  3. <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  4. Save and then close the MyWebPart.csproj file.
  5. Right-click on the MyWebPart project and select Reload Project.
  6. Right-click on the MyWebPart project and select Properties On the Application tab, change the Target Framework to be .NET Framework 3.5. Save the changes.

Creating the ASP.NET User Control

This procedure demonstrates how to create an ASP.NET user control that uses SharePoint.

To create the ASP.NET user control

  1. In Visual Studio, right-click the TEMPLATE folder, select Add then click New Folder. Name the folder CONTROLTEMPLATES.
  2. Right-click the CONTROLTEMPLATES folder, select Add then click New Folder. Name the folder MyWebPart
  3. Right-click the MyWebPart folder, select Add then click New Item.
  4. In the Categories pane, click Web. In the Templates pane, click Web User Control. Name the control MyWebUserControl.ascx, and then click Add.
  5. Delete the CodeBehind attribute in the MyWebUserControl.ascx file. Replace the Inherits attribute with MyWebPart.MyWebUserControl, MyWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[your PublicKeyToken]. The following code shows the corrected file:
  6. <%@ Control Language="C#" AutoEventWireup="true" Inherits="MyWebPart.MyWebUserControl, MyWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9410bf5b454f3bbd" %>
  7. Open the MyWebUserControl.ascx file in the designer view. Click the Toolbox, and then add a Label using a drag-and-drop operation. Switch to the code view and rename the ID property to be MyLabel.
  8. Open the MyWebUserControl.ascx.cs file and the MyWebUserControl.ascx.designer.cs file. Change the namespace to MyWebPart in both files.
  9. Open the MyWebUserControl.ascx.cs file. Add a public string property named DisplayText to the MyWebUserControl class. The following code demonstrates this:
  10. public string DisplayText { get; set; }
  11. Add the following code to the Page_Load method. This will display the value of the DisplayText property using the MyLabel control.
  12. protected void Page_Load(object sender, EventArgs e)
    {
        MyLabel.Text = DisplayText;
    }

Wrapping the User Control and Connecting the Properties

This procedure demonstrates how to wrap the user control inside the web part and connect the properties between SharePoint, the web wart and the user control.

To wrap the user control and connect the properties

  1. Open the MyWebPart.cs file.
  2. Edit the attributes of the MyProperty property. The code below shows the changes:
  3. [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [System.ComponentModel.Category("Custom")]
    [WebDisplayName("MyProperty")]
    [WebDescription("Message to be displayed within Web Part")]
    
  4. Within the CreateChildControls() method, delete the single line of code under the // Your code here... comment. Enter code to load the MyWebUserControl, assign the value of MyProperty to the DisplayText property of the control and then add the control to the web part’s Controls collection. The code below demonstrates how to do this:
  5. // Your code here...
    MyWebUserControl myControl = 
       (MyWebUserControl)Page.LoadControl("~/_controltemplates/MyWebPart/MyWebUserControl.ascx");
    myControl.DisplayText = MyProperty;
    this.Controls.Add(myControl);
    
  6. Right-click on the MyWebPart solution and select Rebuild Solution.

The completed solution structure is shown below:

SolutionStructure

Deploying the Web Part and Testing Functionality

This procedure demonstrates how to deploy the web part and the user control, and how to test their functionality. This procedure assumes that there is a local instance of SharePoint to deploy to.

To deploy the web part

  1. Right-click on the MyWebPart project, select WSPBuilder and then Build WSP. Follow the progress of the build in the Output window and wait for the process to complete.
  2. Right-click on the MyWebPart project, select WSPBuilder and then Deploy. Follow the progress of the build in the Output window and wait for the process to complete.
  3. Browse to the local SharePoint site.
  4. In the Site Actions drop-down box, click Site Settings. On the Site Settings page, click on the Site features link.
  5. Click on the Activate button next to the My Web Part feature.
  6. Click on the link to the default home page for the SharePoint site.
  7. In the Site Actions drop-down box, click Edit Page.
  8. Click Add a Web Part in one of the Web Part zones on the page, click the My Web Part Web Part (located in the My Group section), and then click Add.
  9. Click Exit Edit Mode. You should now see the default “Hello SharePoint” message.
  10. To change the text displayed, click the drop-down box on the Web Part, and then click Modify Shared Web Part.
  11. Expand the Custom group, enter the new display message in the My Property box, and then click Apply.
  12. Click Exit Edit Mode. You should now see the new message.

Notes

  1. Obtaining the PublicKeyToken from the compiled assembly is detailed in numerous places however I recommend Todd Bleeker’s blog.
  2. The MyWebPart.cs file produced by WSPBuilder contains much more “helper” code than that created by VSeWSS. Although this is useful in that it provides an example of a browsable web part property and some hints on where to place customisations, most of the code can be stripped out if required. Only the CreateChildControls() method is mandatory.
  3. WSPBuilder will deploy to all web applications within the local SharePoint farm.
  4. Take care over providing the correct path to the user control when calling the LoadControl() method.

Alternatives

As an alternative to modifying the ProjectTypeGuid property, it is possible to add an ASP.NET Web Application project to the solution and then xcopy the project outputs to the correct location within the WSPBuilder project.

Greg Galipeau provides a excellent walkthrough of this approach.

Advertisements
  1. Biju
    September 18, 2009 at 11:36 am

    Hi,
    I have developed an event handler,called TaskListEventHandler, for the Task list ((ItemAdding, ItemDeleting, ItemUpdating) as feasture using the WSP Builder project template, and I have also added a web part, called RegisterEventHandler, which will be used to bind(register) the events to a list. The webpart is WSP Builder template “Webpart without feature”.

    Currently, on deployment, my feature and the webpart is getting deployed sucessfully. The web part is also available in the web part gallery.

    Now i need to make the web part available in a particular category/group in the gallery using the WSP Builder?

    Whereas , when i try to deploy the.wsp using the stsadm manually the grouping is getting set sucessfully.

    I tried setting the group in the RegisterEventHandler.webpart file (which is automatically created by WSP builder on adding the webpart template inot the project), but still it doesn’t show up 😦

    Could anyone please help or suggest me some solution or sample code?

  2. Neeraj Sehgal
    November 19, 2009 at 6:25 am

    Hi Iam getting following error while deploying listView user control through web part.’ReminderWebPart.ReminderWebPart, ReminderWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=87ed51351ebe7c43′ is not allowed here because it does not extend class ‘System.Web.UI.UserControl’

    Please suggest any workaround.

    • oidatsmyleg
      December 11, 2009 at 3:30 pm

      Your user control class needs to extend System.Web.UI.Control:

      public partial class MyUserControl : System.Web.UI.UserControl
  3. omer bulbul
    December 18, 2009 at 1:30 pm

    great description, thank you so much

  4. Ash
    April 29, 2010 at 7:26 pm

    Hi there,

    It worked very well indeed – so thank you!

    Can you tell me how I can use an ascx code-behind file (as your tutorial removes it?

    Thanks, Ash

  5. Ash
    April 30, 2010 at 2:39 pm

    Hi Oidatsmyleg,

    As to my previous question, I’ve figured it out now thank you!

    Thank you for a wonderful tutorial. A lot of other sites have tutorials that claim to be ‘step-by-step’, but half of them are wrong, or are ‘shortcuts’ where vital steps have been missed out. Thank you for all the detailed steps! You’ve solved something that I’ve been trying to achieve for a while.

    Much Obliged,

    Ash

  6. November 5, 2010 at 6:48 am

    Hi,

    I added one label in my usercontrol.ascx and assigned text to it on the page load of usercontrol.ascx.cs. Deployed the solution and added the webpart to my page successfully.
    Next time i deleted the label from design and removed the code behind and i started getting “Object reference not set to an instance of an object” error. Please let me know how can i resolve this issue.

    Saurabh

  7. Jowico
    February 10, 2011 at 12:25 am

    Excellent post!
    just what I needed. Many thanks.

  8. May 18, 2011 at 1:24 pm

    Thank very much !!

    This approach saved my time alot !

  1. February 8, 2011 at 11:20 am
  2. September 25, 2013 at 11:10 pm

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: