Monday 16 July 2012

Add a Web Part Using Object Model

Add a new webpart page MyPage1.aspx on your site(http://localhost/sites/MyNewSite) in 'Shared Document' document library.

Create a Console application and add following references and code.

Assembly References 
• Windows SharePoint Services 
• System.Web assembly 
• MyNewWebPart assembly 

Class Library References 
• Microsoft.SharePoint
• Microsoft.SharePoint.WebControls; 
• Microsoft.SharePoint.WebPartPages; 
• System.Web
• MyNewWebPart


Code - 

SPSite site = new SPSite("http://localhost/sites/MyNewSite");
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
SPLimitedWebPartManager webParts = web.GetLimitedWebPartManager("Shared Documents/MyPage1.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

//Create an instance of Custom Webpart and add in a Webpart zone
MyNewWebPart.MyWelcomePart wp = new MyWelcomePart();
wp.Title = "My WebPart Using OM";
webParts.AddWebPart(wp, "Left", 0);
webParts.SaveChanges(wp);

//Create an instance of CEWP and add in a Webpart zone
Microsoft.SharePoint.WebPartPages.ContentEditorWebPart cewp = new Microsoft.SharePoint.WebPartPages.ContentEditorWebPart();
XmlDocument xmlDoc = new XmlDocument();
System.Xml.XmlElement xmlElem = xmlDoc.CreateElement("xmlElem");
xmlElem.InnerText = "Hello From CEWP!";
cewp.Content = xmlElem;
cewp.Title = "My CEWP Using OM";
webParts.AddWebPart(cewp, "Left", 0);
webParts.SaveChanges(cewp);

//Create an instance of Page Viewer Webpart and add in a Webpart zone
Microsoft.SharePoint.WebPartPages.PageViewerWebPart pvwp = new Microsoft.SharePoint.WebPartPages.PageViewerWebPart();
pvwp.SourceType = PathPattern.URL;
pvwp.ContentLink = "http://www.google.com";
pvwp.Title = "My PVWP Using OM";
webParts.AddWebPart(pvwp, "Left", 0);
webParts.SaveChanges(pvwp);

web.Update();
web.Dispose();
site.Dispose();



Very useful code that how can we add custom and/or Default web part from here.

No comments :

Post a Comment