In this post I will explian how to build a custom WebPart for SharePoint 2007 and how to use ASP.NET Web User Control in it. I am using Visual Studio 2008 for the development.
Following are the steps to create a custom webpart and calling/loading Web User Control in it:
Building WebPart and Web User Control project
- Craete ASP.NET Web Application Project.
- Delete Default.aspx.
- Add two new folders: UserControls and WebPart into the solution.
- Add new Web User Control in UserControls folder.
- Add new CS Class file TrainingWP.cs in WebPart folder.
- Add reference to SharePoint.dll (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll)
- Add followign code to TrainingWP.cs
- Go to Tools -> Create GUID and copy/paste GUID above the class and add reference using System.Runtime.InteropServices; line.
- Open code behind for Web User Control and add using Microsoft.SharePoint; line and in Page_Load function write hello world code and build the solution.
public class TrainingWP : WebPart
private Control uc = null;
private string ucPath = "~/UserControls/TrainingUC.ascx";
protected override void CreateChildControls()
uc = Page.LoadControl(ucPath);
catch (Exception ex)
We are overriding the CreateChildControls method of the WebPart class in which we will load the Web User Control.
Deploying the WebPart and the Web User Control
- In Project Properties -> Build Event tab -> Post-build Event Command add following line:
"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\gacutil.exe" /i $(TargetPath)
This will deploy our webpart dll into GAC after building the solution.
- In Project Properties -> Signing tab -> check Sign Assembly -> and give a name.
- Build the solution and WebPart should be deployed into GAC (c:\Windows\assembly).
- Create DWP File using following XML
- Upload DWP file to WebPart Gallery. DWP file tells SharePoint to load which library when webpart is called.
- Open the root folder of the Web Application and edit Web.config. Under <SafeControls> add following line
- Under <assemblies> in Web.config add following line
- Copy UserControls folder in to the root folder of the Web Application.(Just copy ASCX)
- Do iisreset and add the WebPart on the page through Web UI of the site.
Cannot import this Web Part.
Training Web Part
Thats it :o). Happy Programming.