How to programmatically add a content editor web part

I was having some trouble adding to a page a ContentEditorWebPart with some custom HTML content. All that you need to do to define the content is to create a XmlDocument instance with an XmlElement with your HTML as its inner text.

// TODO: open web and checkout page

ContentEditorWebPart contentEditor = new ContentEditorWebPart();

XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement("HtmlContent");
xmlElement.InnerText = "<strong>Hello World!</strong>";
contentEditor.Content = xmlElement;

using (SPLimitedWebPartManager manager =
  web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared)) {
 manager.AddWebPart(contentEditor, zoneID, zoneIndex);
}

// TODO: publish page

When adding the web part to a page, you have to specify the web part zone ID and the index that you want the web part to be place at in the zone.

You can get the appropriate zone ID from your masterpages/page layouts.

Nuno Freitas
Posted by Nuno Freitas on September 30, 2013

Related articles