Thursday, May 1, 2008

Adding a Custom web part to SharePoint and MOSS

Below is a method that shows how you can add a custom web part to SharePoint
 
public static void AddCustomWebPart(SPWeb web
, System.Web.UI.WebControls.WebParts.WebPart webPart
, string fullOrRelativeUrl
, PersonalizationScope scope
, string webPartZoneID
, int webPartZoneIndex)
{
SPLimitedWebPartManager wpManager =
web.GetLimitedWebPartManager(fullOrRelativeUrl, scope);

wpManager.AddWebPart(webPart, webPartZoneID, webPartZoneIndex);
}


The code looks pretty easy but it wasn't immediately obvious to me at the beginning. I struggled to find the second param webPart. Initially I looked within SharePoint to see if I could find it, you would think that you could look in the web part gallery find the web part and add it. This was not the case.

The easiest way I found was to deploy the web part as standard to your site. Then include the complied .dll for your custom web part as reference in your deployment console or feature receiver.

A sample usage is below. Notice I have included the "using SampleSharePointSolution.WebPart;" now I can pass new HelloWebPart() as the web part param.

 
using SampleSharePointSolution.WebPart;

namespace DeploymentConsole
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://vm-spdev-7497:1000/"))
{
using (SPWeb web = site.RootWeb)
{
Deploy.AddCustomWebPart(web
, new HelloWebPart()
, "Default.aspx"
, PersonalizationScope.Shared
, "Left"
, 0);
}
}
}
}
}

No comments: