Friday, October 22, 2010

Add Web Part to page using C# code in SharePoint

Add Web Part to page using C# code in SharePoint:

In MOSS 2007 or WSS 3.0 sites we can add or remove the web part from SharePoint page, using the options available in site. We can also add web part into a page using SharePoint Object Model. To add web part into a page, we will use SPLimitedWebPartManager class.

SPLimitedWebPartManager class:

Provides a limited set of Web Part operations that can be performed in our object model scenarios when there is no HttpContext and no Page object is instantiated.


Example 1: Add web part to a page by passing page Url, webPart Name, zoneID and zoneIndex:-


Using Microsoft.Sharepoint;
Using System.Web.UI.WebControls.WebParts;


public static string AddWebPartToPage(
SPWeb web,
string pageUrl,
string webPartName,
string zoneID,
int zoneIndex)
{
using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
using (WebPart webPart =

CreateWebPart(web, webPartName, webPartManager))
{
webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
}
}

public static WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager)
{
SPQuery qry = new SPQuery();
qry.Query = String.Format(CultureInfo.CurrentCulture,
"{0}",
webPartName);

SPList webPartGallery = null;

if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}

SPListItemCollection webParts = webPartGallery.GetItems(qry);

XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMsg;
WebPart webPart = webPartManager.ImportWebPart(xmlReader, out errorMsg);

return webPart;
}


Example 2: Add Content Editor web part to a page by passing site Url and page relative URL:-





public static string AddWebPartToPage(
string siteURL,
string pageRelativeUrl,
)
{




using (SPSite site = new SPSite(siteURL))
{
SPWeb web = site.RootWeb;
SPFile page = web.GetFile(pageRelativeUrl);
page.CheckOut();
using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
XmlElement p = new XmlDocument().CreateElement("p");
p.InnerText = "Hello World";
ContentEditorWebPart cewp = new ContentEditorWebPart();
cewp.Content = p;
wpmgr.AddWebPart(cewp, "Header", 0);
}
page.CheckIn(String.Empty);
}


}



References for this article:

http://www.dhirajranka.com/?p=78
Share:

0 comments:

About Me

My photo
Based in Bangalore, INDIA, Amit is a MCC. He has an MCA from the U.P.T.U., INDIA and holds Microsoft certifications including SharePoint 2007/2010/2013. He is an contributor to MSDN and http://amitkumarmca04.blogspot.com/. Amit have experience in SharePoint,ASP.Net with C#, Classic ASP, VB,Macros,HTML,JavaScript,JSON,BootStrap and AngularJS.

Followers

Labels