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.
namespace Training
{
[Guid("2E4AFAAA-AE99-4e15-9972-E6195EFBDD9C")]
public class TrainingWP : WebPart
{
private Control uc = null;
private string ucPath = "~/UserControls/TrainingUC.ascx";
protected override void CreateChildControls()
{
try
{
uc = Page.LoadControl(ucPath);
this.Controls.Add(uc);
}
catch (Exception ex)
{
throw ex;
}
finally
{
base.CreateChildControls();
}
}
}
}
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.
Hi,I am a web designer and internet marketer who is ready to share the many things in Web Design Cochin I've worked so hard to learn. Why do I teach this for free? Because I think that nobody should have to pay in order to learn how to design a website. This is my message and here is my website please visit and learn all you need.Thanks.....
ReplyDelete