Thursday, May 13, 2010

how to Add a Web Part to SharePoint Page Dynamically

THere will be two steps involved in adding an existing webpart to an existing webpart page.
1. Get the webpart from the webpart gallery.
2. Then add it to the page into the target web part zone.
All manipulations with a web part on a page are governed by the SPLimitedWebPartManager class, which is a scaled down version of SPWebPartManager class.

public string AddWebPartToPage(
SPWeb web,
string pageUrl,
string webPartName,
string zoneID,
int zoneIndex)
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart =
CreateWebPart(web, webPartName))
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
manager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
}
}

The CreateWebPart() method first constructs a CAML query, which will look up the web part in a web part gallery. Certainly this means that for the method to work the web part must already be in the web part gallery


private System.Web.UI.WebControls.WebParts.WebPart
CreateWebPart(SPWeb web, string webPartName)
{
SPQuery query = new SPQuery();
query.Query = String.Format(
"{0}",
webPartName);

SPList webPartGallery = null;

if (null == web.ParentWeb)
{
// This is the root web.
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
// This is a sub-web.
webPartGallery = web.ParentWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}

SPListItemCollection webParts = webPartGallery.GetItems(query);

string typeName = webParts[0].GetFormattedValue("WebPartTypeName");
string assemblyName = webParts[0].GetFormattedValue("WebPartAssembly");
ObjectHandle webPartHandle = Activator.CreateInstance(
assemblyName, typeName);

System.Web.UI.WebControls.WebParts.WebPart webPart =
(System.Web.UI.WebControls.WebParts.WebPart)webPartHandle.Unwrap();
return webPart;
}

No comments: