How to assign content to a CMSEditableRegion control via the code-behind

This article describes how to assign content to a CMSEditableRegion control defined in the ASPX template, from within the code-behind.
The content of the CMSEditableRegion control or the EditableText web part is bound to a document and you would usually have to insert content in the Page tab in CMSDesk / Content / Edit mode.

On occasion, you may want to insert some content or assign a value to a given CMSEditableRegion from within the code-behind, without having to access the CMSDesk and doing it manually. This can be useful when you want to change the content dynamically, for instance.
Let’s see how it can be done. First, suppose that we have the following control defined in the ASPX template:
<cms:CMSEditableRegion runat="server" ID="toptext" RegionType="HtmlEditor" RegionTitle="My editable region" />

Then, we can set its content in the code-behind like this:
//Get PageInfo
System.Guid g = new Guid("68846B3F-1C79-4C9D-8BDB-B4BC0414D2FE");
PageInfo pi = PageInfoProvider.GetPageInfo(g);
//Set value
pi.EditableRegions["toptext"] = "Some content";
TreeProvider tr = new TreeProvider();
TreeNode tn = tr.SelectSingleNode(CMSContext.CurrentDocument.DocumentID);
// Update the content XML
tn.SetValue("DocumentContent", pi.DocumentContent);
// Update the document
DocumentHelper.UpdateDocument(tn, tr);

Let’s look more deeply at the code above.
First, we need to get a PageInfo object. You can get it according to the document GUID, as I did, or by using an Alias path or URL path. More info can be found in the API reference file.
The method belongs to the CMS.PortalEngine.PageInfoProvider class. The “toptext” is an ID (key) of the given control in the EditableRegions collection. When you debug it, you can see all such controls and their names and values within the document.

See also: API Reference

Applies to: Kentico CMS 6.x
Share this article on   LinkedIn