How to: Wrap a User Control Inside of a Web Part for SharePoint

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

This topic demonstrates how to create a Web Part to serve as a wrapper for an ASP.NET user control that is hosted inside of a SharePoint application. It also demonstrates how to create Web Part properties that are propagated to the user control. The topic uses Windows SharePoint Services 3.0 Tools: Visual Studio 2008 Extensions, Version 1.2.

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 SharePoint. In the Templates pane, click Web Part. In the Name box, type MyWebPart, and then click OK.

  3. Rename the WebPart1 folder to MyWebPart. Inside the folder are three files named WebPart1.cs, WebPart1.webpart, and WebPart1.xml. Rename each file to MyWebPart (keeping the appropriate file name extension for each file).

  4. Change the class name of the WebPart1 class in the MyWebPart.cs file to MyWebPart, and then delete the constructor of the class. The following code shows the corrected file.

    public class MyWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
    
    
      protected override void CreateChildControls()
      {
        base.CreateChildControls();
    
        // TODO: add custom rendering code here.
        // Label label = new Label();
        // label.Text = "Hello World";
        // this.Controls.Add(label);
      }
    }
    
  5. Open the MyWebPart.webpart file and replace all instances of WebPart1 with MyWebPart. The following code shows the corrected file.

    <webParts>
      <webPart xmlns="https://schemas.microsoft.com/WebPart/v3">
        <metaData>
          <!--
          The following Guid is used as a reference to the web part class, 
          and it will be automatically replaced with actual type name at
          deployment time.
          -->
          <type name="61ed6d82-91e5-4ef3-910e-33d0f771341e" />
          <importErrorMessage>Cannot import MyWebPart Web  Part.</importErrorMessage>
        </metaData>
        <data>
          <properties>
            <property name="Title" type="string">MyWebPart Web Part</property>
            <property name="Description" type="string">MyWebPart Description</property>
          </properties>
        </data>
      </webPart>
    </webParts>
    
  6. Open the MyWebPart.xml file and replace all instances of WebPart1 with MyWebPart. The following code shows the corrected file.

    <Elements Id="61ed6d82-91e5-4ef3-910e-33d0f771341e" xmlns="https://schemas.microsoft.com/sharepoint/" >
      <Module Name="WebParts" List="113" Url="_catalogs/wp">
        <File Path="MyWebPart.webpart" Url="MyWebPart.webpart" Type="GhostableInLibrary" />
      </Module>
    </Elements>
    

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 MyWebPart solution, point to Add, and then click New Project.

  2. In the Project Types pane, click Web. In the Templates pane, click ASP.NET Web Application. Name the project MyUserControl, and then click OK.

  3. Delete the Default.aspx file.

  4. Right-click the MyUserControl project, point to Add, and then click New Item.

  5. In the Categories pane, click Web. In the Templates pane, click Web User Control. Name the control MyUserControl.ascx, and then click Add.

  6. Delete the CodeBehind attribute in the MyUserControl.ascx file. The following code shows the corrected file.

    <%@ Control Language="C#" AutoEventWireup="true" Inherits="MyUserControl.MyUserControl" %>
    
  7. Right-click the MyWebPart project, point to Add, and then click New Folder. Name the folder Templates.

  8. Right-click the Templates folder, point to Add, and then click New Folder. Name the folder ControlTemplates.

  9. Right-click the ControlTemplates folder, point to Add, and then click New Folder. Name the folder MyWebPart.

  10. Right-click the MyWebPart folder, point to Add, and then click Existing Item. Browse to the MyUserControl.ascx file, and then click Add as Link in the drop-down box.

  11. In the MyUserControl project, open the MyUserControl.ascx file. Replace the existing value of the Inherits attribute with MyWebPart.MyUserControl, MyWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5. This allows the code behind to be compiled into the MyUserControl.dll. The following code shows the corrected file.

    <%@ Control Language="C#" AutoEventWireup="true"  Inherits="MyWebPart.MyUserControl, MyWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" %>
    
  12. In the MyUserControl project, open the MyUserControl.ascx file in the designer view. Click the Toolbox, and then add a panel using a drag-and-drop operation.

  13. In the MyUserControl project, open the MyUserControl.ascx.cs****file and the MyUserControl.ascx.designer.cs file. Change the namespace to MyWebPart in both files.

  14. In the MyUserControl project, right-click References, and then click Add Reference. In the Add Reference box, click Windows SharePoint Services. This adds a reference to the Microsoft.SharePoint namespace.

  15. In the MyUserControl.ascx.cs file, add a using statement for the Microsoft.Sharepoint namespace and for the System.Drawing namespace. The following code shows the using statements.

    using Microsoft.SharePoint;
    using System.Drawing;
    
  16. In the MyUserControl.ascx.cs file, if applicable, remove the using statements for System.Data, System.Linq, System.Xml.Linq, and System.Xml.

  17. In the MyUserControl project, open References. Right-click System.Data, and then click Remove. Do the same for System.Linq, System.Xml.Linq, and System.Xml, if applicable.

  18. In the MyWebPart project, right-click References, and then click Add References. In the Add Reference box, click System.Drawing.

  19. In the MyUserControl project, open the MyUserControl.ascx.cs file. Add a public SPWeb property named Web to the MyUserControl class. The following code demonstrates this.

    public SPWeb Web { get; set; }
    
  20. Add a public string property named TextColor to the MyUserControl class. The following code demonstrates this.

    public string TextColor { get; set; }
    
  21. Add the following code to the Page_Load method. This code modifies the Style property of the Panel1 panel with the value of the user-defined TextColor property. It also displays the name of the current user inside of the panel.

    protected void Page_Load(object sender, EventArgs e)
    {
        if ( !String.IsNullOrEmpty(this.TextColor) )
        {
            Color myColor = Color.FromName(this.TextColor);
            if ( myColor != null )
            {
                Panel1.Style.Add("color", myColor.Name);
            }
        }                     
    
        string currentUser = this.Web.CurrentUser.Name;
        Panel1.Controls.Add(new LiteralControl(String.Format("Hello {0}!", currentUser)));
    }
    
  22. Right-click the MyWebPart solution, and then click Build Solution.

Wrapping the User Control and Connecting the Properties

This procedure demonstrates how to wrap the user control inside of the Web Part and connect the properties between SharePoint, the Web Part, and the user control.

To wrap the user control and connect the properties

  1. In the MyWebPart project, open the MyWebPart.cs file.

  2. Add a public string property named TextColor to the MyWebPart class. Add the following attributes to the TextColor property. These properties are specific to Web Parts. They customize the rendering oftheproperty while the Web Part is in Edit mode in SharePoint. This code demonstrates how to do this.

    /// <summary>
    /// The color of the text to set in the child user control.
    /// </summary>
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Text Color")]
    [WebDescription("Color of text in the main content of the Web Part.")]
    [SPWebCategoryName("Development")]
    public string TextColor
    {
        get;
        set;
    }
    
  3. Replace the TODO comments in the CreateChildControls method with the following code. This code loads the MyUserControl user control and adds it to the Web Part. If the user control is not found, an error message is displayed.

    try
    {
        // Loads a user control
        MyUserControl myUserControl = (MyUserControl)Page.LoadControl("~/_controltemplates/MyWebPart/MyUserControl.ascx");
        myUserControl.Web = SPContext.Current.Web;
        myUserControl.TextColor = this.TextColor;
    
        // Adds it to the controls collection of the Web Part 
        this.Controls.Add(myUserControl);
    }
    catch ( HttpException ex )
    {
        this.Controls.Add(new LiteralControl("<br />An unexpected error occurred loading Web Part. " + ex.Message));
    }
    
  4. Add a using statement for the System.Web namespace. The following code demonstrates how to do this.

    using System.Web;
    
  5. Rebuild the solution.

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 you already have an instance of a SharePoint site installed.

To deploy the Web Part

  1. Right-click the MyWebPart project, and then click Properties.
  2. On the Debug tab, type the URL of your SharePoint test site in the Start browser with URL box.
  3. Right-click the MyWebPart project, and then click Deploy.
  4. Browse to your SharePoint test site home page.
  5. In the Site Actions drop-down box, click Edit Page.
  6. Click Add a Web Part in one of the Web Part zones on the page, click the MyWebPart Web Part****(located in the Miscellaneous section), and then click Add.
  7. Click Exit Edit Mode. You should now see a "hello" message with your user name in black text.
  8. To change the color of the text, click the drop-down box on the Web Part, and then click Modify Shared Web Part.
  9. Expand the Development group, enter the name of a valid color, such as Blue, in the Text Color box, and then click Apply.
  10. Click Exit Edit Mode. You should now see a "hello" message with your user name in blue text.

For more information about this topic, see Developing Web Parts in Windows SharePoint Services on MSDN.

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Footer image

To provide feedback, get assistance, or download additional, please visit the SharePoint Guidance Community Web site.

Copyright © 2008 by Microsoft Corporation. All rights reserved.