Saturday, July 12, 2008

Using User Control in Sharepoint Web Parts

Web parts are more complicated to implement than user controls. So often people will desire to use user control in web parts. In this case, I will create a user control which contains a repeater to show some information within a custom news list in a MOSS site.


1. Create a user control called News.ascx. Make sure you specify this user control to inherit from the solution assembly. By the way, if you do not have a solution set up yet, I recommend you try out
STSDEV, this is what I am using in this example.


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="News.ascx.cs" Inherits="ATSDeploymentSolution.News,ATSDeploymentSolution, Version=, Culture=neutral, PublicKeyToken=ca6621b7467269f9" %>

<asp:Repeater ID="repNews" runat="server">





<div><%# Eval("ID") %>: <%# Eval("Title") %></div>








// <auto-generated>

// This code was generated by a tool.

// Runtime Version:2.0.50727.1433


// Changes to this file may cause incorrect behavior and will be lost if

// the code is regenerated.

// </auto-generated>


Namespace ATSDeploymentSolution


/// <summary>

/// SimpleList class.

/// </summary>

/// <remarks>

/// Auto-generated class.

/// </remarks>

public partial class News {

protected global::System.Web.UI.WebControls.Repeater repNews;




using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Microsoft.SharePoint;

Namespace ATSDeploymentSolution


public partial class News : System.Web.UI.UserControl


protected void Page_Load(object sender, EventArgs e)


if (!IsPostBack)





private void Bind()


using (SPSite site = new SPSite("http://w2k3sharepoint:43490"))


using (SPWeb web = site.OpenWeb())


SPList list = web.Lists["ATSNews"];

repNews.DataSource = list.Items.GetDataTable();







2. Put this user control under the CONTROLTEMPLATES folder which is used to store all the user controls under the 12 hive. You can also notice from this image that I have created a feature called ATSDeploymentSolution which contains a bunch of web parts. ATSHomeNewsWebPart is the web part we will use to load the user control from.

3. Modify the manifest.xml to include this template file. The modified part is highlighed in red.

<?xml version="1.0" encoding="utf-8"?>

<!--Manifest created STSDEV utility at 22/05/2008 11:42:17 AM-->

<Solution SolutionId="4508B2DF-131A-4C52-A806-7C92AFD703A3" ResetWebServer="True" xmlns="">

<!--Feature Manifest files-->


<FeatureManifest Location="ATSDeploymentSolution\feature.xml" />

<FeatureManifest Location="ATSWorkflow\feature.xml" />

<FeatureManifest Location="ATSNewsletterListEvents\feature.xml" />


<!--TEMPLATE files-->


<TemplateFile Location="IMAGES\ATSDeploymentSolution\AfricanPith32.gif" />

<TemplateFile Location="IMAGES\ATSDeploymentSolution\Thumbs.db" />

<TemplateFile Location="ControlTemplates\SimpleList.ascx" />

<TemplateFile Location="ControlTemplates\News.ascx" />


<!--Assembly files-->


<Assembly Location="ATSDeploymentSolution.dll" DeploymentTarget="GlobalAssemblyCache">


<SafeControl Assembly="ATSDeploymentSolution, Version=, Culture=neutral, PublicKeyToken=ca6621b7467269f9" Namespace="ATSDeploymentSolution" TypeName="*" Safe="True" />





4. Specify the path of news.ascx in the SolutionPackage.ddf. The modified part is highlighed in red.

; Generated by STSDEV at 22/05/2008 11:42:17 AM


.Set CabinetNameTemplate=ATSDeploymentSolution.wsp

.set DiskDirectoryTemplate=CDROM

.Set CompressionType=MSZIP

.Set UniqueFiles=off

.Set Cabinet=on

.Set DiskDirectory1=DeploymentFiles

;*** Solution manifest


;*** Assembly files


;*** add files for ATSDeploymentSolution feature

.Set DestinationDir=ATSDeploymentSolution



;*** add files for ATSDeploymentSolution\WebParts feature

.Set DestinationDir=ATSDeploymentSolution\WebParts








;*** add files for ATSWorkflow feature

.Set DestinationDir=ATSWorkflow



;*** add files for ATSNewsletterListEvents feature

.Set DestinationDir=ATSNewsletterListEvents



;*** Begin TemplateFiles section ***


.Set DestinationDir=IMAGES\ATSDeploymentSolution



.Set DestinationDir="ControlTemplates"



5. Create the web part to load the user control we created.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

Namespace ATSDeploymentSolution


public class ATSHomeNewsWebPart : WebPart


News _news = null;

protected override void CreateChildControls()



_news = (News)Page.LoadControl("~/_controltemplates/News.ascx");





6. Create the webpart xml file and put it under the WebParts folder of the ATSDeploymentSolution Feature.

<?xml version="1.0" encoding="utf-8"?>

<!--Created by STSDEV at 8/05/2008 10:56:56 AM-->


<webPart xmlns="">


<type name="ATSDeploymentSolution.ATSHomeNewsWebPart, ATSDeploymentSolution, Version=, Culture=neutral, PublicKeyToken=ca6621b7467269f9" />

<importErrorMessage>Error importing Web Part</importErrorMessage>




<property name="Title" type="string">ATSHomeNewsWebPart</property>

<property name="Description" type="string">A webpart for news on the home page.</property>

<property name="ChromeState" type="chromestate">Normal</property>

<property name="AllowZoneChange" type="bool">True</property>

<property name="AllowHide" type="bool">True</property>

<property name="ExportMode" type="exportmode">All</property>





7. Add ATSHomeNewsWebPart.webpart to the SolutionPackage.ddf file. This is highlighted in blue in the above code.

8. Add ATSHomeNewsWebPart.webpart to the Feature.xml of the ATSDeploymentSolution Feature. Highlighted in red.

<?xml version="1.0" encoding="utf-8"?>

<!--Created by STSDEV at 8/05/2008 11:12:24 AM-->



Title="ATS Web Parts Feature"

Description="This SharePoint solution was created by the Sam Fu."




ImageUrl="ATSTestSolution\AfricanPith32.gif" xmlns="">



Location="WebParts.xml" />


Location="WebParts\ATSCompanySearchWebPart.webpart" />


Location="WebParts\ATSGlobalSearchWebPart.webpart" />


Location="WebParts\ATSNewsSearchWebPart.webpart" />


Location="WebParts\ATSNewsletterSearchWebPart.webpart" />


Location="WebParts\ATSEventSearchWebPart.webpart" />


Location="WebParts\ATSHidePageWebPart.webpart" />


Location="WebParts\ATSHomeNewsWebPart.webpart" />



9. Add ATSHomeNewsWebPart.webpart to the WebParts.xml which is the ElementManifest of the ATSDeploymentSolution Feature. Highlighted in red.

<?xml version="1.0" encoding="utf-8"?>

<!--Created by STSDEV at 8/05/2008 10:56:56 AM-->

<Elements xmlns="">

<Module Name="ATSDeploymentSolution" List="113" Url="_catalogs/wp" Path="WebParts" RootWebOnly="True">

<File Url="ATSCompanySearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />


<File Url="ATSGlobalSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />


<File Url="ATSNewsSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />


<File Url="ATSNewsletterSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />


<File Url="ATSEventSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />


<File Url="ATSHidePageWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />


<File Url="ATSHomeNewsWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />




10. Since I have deployed the solution before, I will choose DebugReploy from the Visual studio and build the solution. If you have deployed this web part before, you need to choose DebugUpgrade and build.

11. Add the web part to the page you want. This is the News List I had:

Here is the result:

Using user control in web parts

  • As you can see from the above example, using user control in web parts works just fine.
  • All you have to do is in CreateChildControls, load the user control and add it to the control tree.
  • And In OnPreRender, you can set public properties of the user control just like any other control.
  • Pros of using user control in web parts
    • Re-use user controls from other application
    • Easier for development than web parts
  • Cons
    • You now have a dependency between the news.ascx file and the solution assembly. If news.ascx is used in lots of different web parts, you may have a versioning issue.
  • You can also use SmartPart for loading user control in MOSS. It allows you to choose which user control to load at run time in the browser. Of course, you could extend the above example to do the same thing as well.
blog comments powered by Disqus