1. Get SPLimitedWebPartManager from SPWeb
2. Create instance of ContentEditorWebPart class
3. Set all properties to that instance
4. Load your contents using CDATA section of xml in XmlDocument
5. Assign XmlElement type to yourwebPartInstance.Content
6. Ask WebPartManager to add that instance to your webpart zone
7. Call SaveChanges of SPLimitedWebPartManger class.
Here is the code
SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager("YourPageUrl", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
//create new webpart object
ContentEditorWebPart webPartInstance = new ContentEditorWebPart();
//set properties of new webpart object
webPartInstance.ZoneID = "YourWebPartZone";
webPartInstance.Title = "Some Title";
webPartInstance.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
webPartInstance.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
//Load your contents using CDATA section of xml
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"
<![CDATA[
<input onlcick="javascript:sayHello();" type="button" value="Say Hello" />
]]>
");
//Get the contents as XmlElement
XmlElement contentsElement = (XmlElement)doc.SelectSingleNode("//Contents");
webPartInstance.Content = contentsElement;
//add new webpart object to webparts collection
wpManager.AddWebPart(webPartInstance, "YourWebPartZone", 0);
wpManager.SaveChanges(webPartInstance);
//update spWeb object
web.Update();
That's it. Enjoy
No comments:
Post a Comment