Wednesday 19 October 2011

Add content editor webpart on a Sharepoint page using Object model


This is how you add a Content editor WebPart on a SharePoint Page using the SharePoint Object model. The below solution when activated will add a content editor webpart on default.apx page.

1. Create a project in Visual Studio 2010 and then add a new feature in that.

2. In your Feature receiver file and add below code to add a Content Editor in your Default.aspx

//Get the page

SPSite site = new SPSite("http://SPsite");
SPWeb web = site.OpenWeb();

// Get the web part collection

SPWebPartCollection coll =
web.GetWebPartCollection("default.aspx",Storage.Shared);

//Create a new webpart with the code below

XmlDocument xmlDoc = new XmlDocument();
XmlElement element = xmlDoc.CreateElement("p");
XmlAttribute align = xmlDoc.CreateAttribute("align");
align.Value = "right";
element.Attributes.Append(align);
element.InnerText = "HTML Markup";
ContentEditorWebPart cwp = new ContentEditorWebPart();
cwp.ChromeType = PartChromeType.None;
cwp.Content = element;

//add it to the page

coll.Add(cwp);

Ads by Google

No comments:

Post a Comment