Tuesday, July 3, 2012

Add the content editor web-part to the page layout progrmatically


Hello All,


Today we will add the content editor web-part to the page layout with the specified the webpart zone and also add some HTML content to the web-part.For that we will use the console application using visual studio 2010.


So first create one window console application using visual studio 2010.


Then add the Microsoft.Sharepoint.dll refence form the ISAPI folder from 14 hive directory( "C:\Program 


Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI").


So below are my source code


namespace AddSampleData
{
class Program
{


static void Main(string[] args)
{
string pageURL = args[0];  //"http://server:port/pages/default.aspx";
string strHTML = "<div>This is my first blog posting</div>"


using (SPSite site = new SPSite(pageURL))
{
   using (SPWeb web = site.OpenWeb())
   {
       AddContentEditorToWebPartZone(web, pageURL, "Zone_ID", strHTML);
   }
}
}


#region To Add webparts with data to page zones
public static void AddContentEditorToWebPartZone(SPWeb web, string url, string zoneId, string content)
{
SPLimitedWebPartManager webpartmanager = web.GetLimitedWebPartManager(url, PersonalizationScope.Shared);
ContentEditorWebPart cewp = new ContentEditorWebPart();
cewp.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;


XmlDocument docXml = new System.Xml.XmlDocument();
XmlElement contentXml = docXml.CreateElement("Content");
contentXml.InnerText = content;
cewp.Content = contentXml;
webpartmanager.AddWebPart(cewp, zoneId, 0);
}
}
}


Now run the console application it will take 1 argument the page url in which we are going to add the content editor webpart.




Regards
Hiren Patel

No comments:

Post a Comment