Content Services

The IContentService interface is the primary entry point for programmatically reading, writing, and otherwise manipulating the HTML document hosted by a WinFormHtmlEditor control. Access it through htmlEditor1.Content. Members fall into three groups: bulk content I/O (get/set body, document, files), targeted insertion (HTML at caret, head injection, scripts), and document inspection (element lookup, attribute access, link and image enumeration). Two sub-services are reachable through this interface: TableAuthoringService for table row/column/cell authoring and MailMerge for host-registered placeholder fields.

All methods operate against the currently active document and fire the editor's normal change notifications. Callers should not invoke these methods from non-UI threads. Methods that depend on a live MSHTML document require the editor to be in WYSIWYG design mode; calls made from source-edit mode are either ignored or return last-loaded data depending on the method.

GetBodyText Method

Returns the plain-text content of the document body, with HTML markup stripped. Use this for indexing, comparison, or display in a non-HTML surface.

Syntax
string GetBodyText();
Returns

string -- the plain-text body content.

Example
string body = htmlEditor1.Content.GetBodyText();

Console.WriteLine($"Plain body has {body.Length} chars");

GetFormattedPlainText Method

Similar to GetBodyText but preserves block-level layout cues such as paragraph line breaks. Try both algorithms and pick the one whose output best matches the host application's expectations.

Syntax
string GetFormattedPlainText();
Returns

string -- the formatted plain-text body.

Example
string formatted = htmlEditor1.Content.GetFormattedPlainText();

File.WriteAllText(@"C:\temp\export.txt", formatted);

SetBodyText Method

Replaces the document body with the supplied plain text. HTML metacharacters (<, >, &) in the input are escaped automatically.

Syntax
void SetBodyText(string text);
Parameters
NameTypeDescription
textstringThe plain text to set as the body content.
Example
htmlEditor1.Content.SetBodyText("Quarterly report draft - 2026 Q1");

GetBodyHtml Method

Returns the HTML markup contained in the document body. The getInXhtml parameter controls whether the output is normalized to XHTML (self-closing void tags, lowercase names, quoted attributes).

Syntax
string GetBodyHtml(bool getInXhtml);
Parameters
NameTypeDescription
getInXhtmlboolIf true, returns XHTML-normalized markup; otherwise the raw MSHTML serialization.
Returns

string -- the body HTML.

Example
string xhtml = htmlEditor1.Content.GetBodyHtml(getInXhtml: true);

XDocument doc = XDocument.Parse("<root>" + xhtml + "</root>");

SetBodyHtml Method

Replaces the document body markup with the supplied HTML. Equivalent to assigning the WinFormHtmlEditor.BodyHtml property.

Syntax
void SetBodyHtml(string bodyHtml);
Parameters
NameTypeDescription
bodyHtmlstringHTML fragment to place between the body open and close tags.
Example
htmlEditor1.Content.SetBodyHtml("<h1>Welcome</h1><p>Edit me.</p>");

GetDocumentHtml Method

Returns the full HTML document including the DOCTYPE, head, and body. Use this when the host needs the complete file payload for save or upload.

Syntax
string GetDocumentHtml();
Returns

string -- the complete document HTML.

Example
string fullDoc = htmlEditor1.Content.GetDocumentHtml();

File.WriteAllText(@"C:\temp\out.html", fullDoc, Encoding.UTF8);

SetDocumentHtml Method

Replaces the entire document with the supplied HTML, including DOCTYPE, head, and body. Equivalent to assigning the WinFormHtmlEditor.DocumentHtml property.

Syntax
void SetDocumentHtml(string docHtml);
Parameters
NameTypeDescription
docHtmlstringThe complete HTML document to load.
Example
string template = File.ReadAllText(@"C:\templates\letter.html");

htmlEditor1.Content.SetDocumentHtml(template);

GetDocumentXml Method

Returns the document content serialized as XML. Useful when the host needs to persist or interchange the document through an XML pipeline.

Syntax
string GetDocumentXml();
Returns

string -- XML representation of the document.

Example
string xml = htmlEditor1.Content.GetDocumentXml();

XDocument.Parse(xml).Save(@"C:\temp\doc.xml");

GetBodyStyleAsDom Method

Returns the body element's style as an mshtml.IHTMLStyle COM pointer. Use this to read or mutate individual CSS properties without parsing the style string. Returns null when no body element is available (e.g. source-edit mode).

Syntax
IHTMLStyle GetBodyStyleAsDom();
Returns

mshtml.IHTMLStyle -- the body style DOM wrapper.

Example
IHTMLStyle style = htmlEditor1.Content.GetBodyStyleAsDom();

if (style != null)

{

    style.backgroundColor = "#fafafa";

    style.color = "#222";

}

GetBodyStyle Method

Returns the value of the body element's style attribute as a CSS declaration string.

Syntax
string GetBodyStyle();
Returns

string -- the inline CSS string.

Example
string css = htmlEditor1.Content.GetBodyStyle();

Debug.WriteLine($"Body inline CSS = {css}");

SetBodyStyle Method

Writes the supplied CSS declaration string to the body element's style attribute, replacing any existing value.

Syntax
void SetBodyStyle(string styleValue);
Parameters
NameTypeDescription
styleValuestringCSS declaration list, for example margin:8px; color:#333.
Example
htmlEditor1.Content.SetBodyStyle("font-family:Segoe UI; padding:12px; color:#222;");

GetBodyClassName Method

Returns the body element's class attribute, or empty string when no class is set.

Syntax
string GetBodyClassName();
Returns

string -- the body class name.

Example
if (htmlEditor1.Content.GetBodyClassName() != "dark")

    htmlEditor1.Content.SetBodyClassName("dark");

SetBodyClassName Method

Sets the body element's class attribute. Pair this with an InsertHtmlBetweenHead call that injects the matching <style> block to switch the document's theme at runtime.

Syntax
void SetBodyClassName(string className);
Parameters
NameTypeDescription
classNamestringThe CSS class name to attach to <body>.
Example
htmlEditor1.Content.SetBodyClassName("print-preview");

GetAllLinkHrefs Method

Returns the list of href attribute values for every anchor (<a>) in the document body. Use this to validate or rewrite outgoing URLs before publication.

Syntax
string[] GetAllLinkHrefs();
Returns

string[] -- array of hyperlink URLs.

Example
foreach (string href in htmlEditor1.Content.GetAllLinkHrefs())

{

    if (!Uri.IsWellFormedUriString(href, UriKind.Absolute))

        Debug.WriteLine($"Broken link: {href}");

}

GetAllImageSources Method

Returns the list of src attribute values for every <img> element in the body, in document order.

Syntax
string[] GetAllImageSources();
Returns

string[] -- array of image source URLs.

Example
string[] images = htmlEditor1.Content.GetAllImageSources();

MessageBox.Show($"Document references {images.Length} image(s).");

InsertHtml Method

Inserts an HTML fragment at the caret position without disturbing focus. The canonical way to plug arbitrary markup into the document from a custom toolbar button. Script blocks are filtered out by this method; use InsertScript for those.

Syntax
void InsertHtml(string htmlText, bool keepSelected);
Parameters
NameTypeDescription
htmlTextstringThe HTML fragment to insert.
keepSelectedboolIf true, the inserted markup remains selected after insertion.
Example
htmlEditor1.Content.InsertHtml("<p>Hello, <b>world</b></p>", keepSelected: false);

InsertText Method

Inserts a plain-text fragment at the caret. HTML metacharacters in the input are escaped (so < becomes &lt;).

Syntax
void InsertText(string text);
Parameters
NameTypeDescription
textstringThe plain text to insert.
Example
htmlEditor1.Content.InsertText(DateTime.Now.ToString("yyyy-MM-dd HH:mm"));

InsertHorizontalRule Method

Inserts an <hr> horizontal-rule element at the caret position.

Syntax
void InsertHorizontalRule();
Example
private void DividerButton_Click(object sender, EventArgs e)

{

    htmlEditor1.Content.InsertHorizontalRule();

}

InsertScript Method

Inserts a script block at the caret position. InsertHtml strips <script> tags; use this method instead when the script must be preserved in the document.

Syntax
void InsertScript(string scriptMarkUp);
Parameters
NameTypeDescription
scriptMarkUpstringThe <script>...</script> markup to insert.
Example
htmlEditor1.Content.InsertScript("<script>console.log('hi');</script>");

InsertHtmlBetweenHead Method

Inserts the supplied HTML inside the document's <head> section. Useful for injecting <style>, <link>, <meta>, or <script> elements that should live in the head rather than in the body.

Syntax
void InsertHtmlBetweenHead(string insertingHtml);
Parameters
NameTypeDescription
insertingHtmlstringThe HTML to append into <head>.
Example
htmlEditor1.Content.InsertHtmlBetweenHead(

    "<style id='theme'>body { background:#222; color:#eee; }</style>");

RemoveHtmlElementFromHeadByTag Method

Removes every element inside <head> whose tag name matches tagName. Tag matching is case-insensitive.

Syntax
void RemoveHtmlElementFromHeadByTag(string tagName);
Parameters
NameTypeDescription
tagNamestringHTML tag name, e.g. link or style.
Example
// Clear all stylesheet links before reapplying a fresh theme.

htmlEditor1.Content.RemoveHtmlElementFromHeadByTag("link");

RemoveHtmlElementFromHeadById Method

Removes the element inside <head> whose id attribute matches the supplied value. No-op when no matching element exists.

Syntax
void RemoveHtmlElementFromHeadById(string id);
Parameters
NameTypeDescription
idstringElement id attribute.
Example
htmlEditor1.Content.RemoveHtmlElementFromHeadById("theme");

RemoveHtmlElementById Method

Removes the element anywhere in the document whose id attribute matches the supplied value.

Syntax
void RemoveHtmlElementById(string id);
Parameters
NameTypeDescription
idstringElement id attribute.
Example
htmlEditor1.Content.RemoveHtmlElementById("legacyBanner");

ChangeElementId Method

Renames the id attribute of the element from oldId to newId. Useful when restructuring a document programmatically.

Syntax
void ChangeElementId(string oldId, string newId);
Parameters
NameTypeDescription
oldIdstringThe existing element id.
newIdstringThe replacement id.
Example
htmlEditor1.Content.ChangeElementId("intro", "introduction");

ElementExists Method

Returns true if an element with the supplied id exists anywhere in the document.

Syntax
bool ElementExists(string elementId);
Parameters
NameTypeDescription
elementIdstringElement id to test.
Returns

bool -- true if found.

Example
if (!htmlEditor1.Content.ElementExists("footer"))

    htmlEditor1.Content.InsertHtml("<div id='footer'>(c) 2026</div>", false);

GetAttributeValueOfAnElement Method

Returns the value of the named attribute on the element with the given id.

Syntax
string GetAttributeValueOfAnElement(string elementId, string attributeName);
Parameters
NameTypeDescription
elementIdstringElement id.
attributeNamestringAttribute name (e.g. href).
Returns

string -- attribute value, or empty string when not set.

Example
string href = htmlEditor1.Content.GetAttributeValueOfAnElement("mainLink", "href");

SetAttributeValueOfAnElement Method

Sets the value of the named attribute on the element with the given id.

Syntax
void SetAttributeValueOfAnElement(string elementId, string attributeName, string value);
Parameters
NameTypeDescription
elementIdstringElement id.
attributeNamestringAttribute name.
valuestringAttribute value.
Example
htmlEditor1.Content.SetAttributeValueOfAnElement("logo", "alt", "Company logo");

GetOuterHtmlOfAnElement Method

Returns the outer HTML (including the element's own tag) of the element with the given id.

Syntax
string GetOuterHtmlOfAnElement(string elementId);
Parameters
NameTypeDescription
elementIdstringElement id.
Returns

string -- outer HTML.

Example
string outerHtml = htmlEditor1.Content.GetOuterHtmlOfAnElement("intro");

Debug.WriteLine(outerHtml);

GetInnerHtmlOfAnElement Method

Returns the inner HTML (the markup between the element's open and close tags) of the element with the given id.

Syntax
string GetInnerHtmlOfAnElement(string elementId);
Parameters
NameTypeDescription
elementIdstringElement id.
Returns

string -- inner HTML.

Example
string innerHtml = htmlEditor1.Content.GetInnerHtmlOfAnElement("sidebar");

UpdateInnerHtmlOfAnElement Method

Replaces the inner HTML of the element with the given id. Existing children are discarded.

Syntax
void UpdateInnerHtmlOfAnElement(string elementId, string newHtml);
Parameters
NameTypeDescription
elementIdstringElement id.
newHtmlstringReplacement inner markup.
Example
htmlEditor1.Content.UpdateInnerHtmlOfAnElement("status", "<b>Updated</b>");

GetHtmlElements Method

Returns a snapshot of every element in the document (or just the body, depending on the argument) as a System.Windows.Forms.HtmlElementCollection, which the host can enumerate to inspect or mutate elements.

Syntax
HtmlElementCollection GetHtmlElements(bool onlyBodyElements);
Parameters
NameTypeDescription
onlyBodyElementsboolIf true, only elements inside <body> are returned; otherwise all document elements.
Returns

System.Windows.Forms.HtmlElementCollection -- the element collection.

Example
var elements = htmlEditor1.Content.GetHtmlElements(onlyBodyElements: true);

foreach (HtmlElement el in elements)

{

    if (el.TagName == "IMG") Debug.WriteLine(el.GetAttribute("src"));

}

GetBodyIHtmlElements Method

Returns the body elements as an mshtml.IHTMLElementCollection COM pointer. Use this when an MSHTML-style API surface is required (for example, when calling COM methods that expect MSHTML interfaces).

Syntax
IHTMLElementCollection GetBodyIHtmlElements();
Returns

mshtml.IHTMLElementCollection -- the body element collection.

Example
IHTMLElementCollection coll = htmlEditor1.Content.GetBodyIHtmlElements();

foreach (IHTMLElement el in coll)

    Debug.WriteLine(el.tagName);

GetHtmlElementAt Method

Returns the topmost element under the supplied document coordinate as an mshtml.IHTMLElement. Useful for hit-testing custom commands or drag-and-drop targeting.

Syntax
IHTMLElement GetHtmlElementAt(Point caretPosition);
Parameters
NameTypeDescription
caretPositionSystem.Drawing.PointDocument-space coordinate.
Returns

mshtml.IHTMLElement -- the element at that point, or null.

Example
IHTMLElement hit = htmlEditor1.Content.GetHtmlElementAt(new Point(120, 80));

if (hit != null) Debug.WriteLine($"Hit: {hit.tagName}#{hit.id}");

EmbedLocalImagesAsBase64 Method

Walks the document looking for <img> elements whose src resolves to a local file and rewrites each one into a Base64-encoded data: URI. After this call the document is self-contained -- safe to email or save as a single HTML file.

Syntax
void EmbedLocalImagesAsBase64();
Example
htmlEditor1.Content.EmbedLocalImagesAsBase64();

string portable = htmlEditor1.Content.GetDocumentHtml();

File.WriteAllText(@"C:\temp\portable.html", portable);

GetEmailMessageWithLocalImagesEmbedded Method

Builds and returns a System.Net.Mail.MailMessage whose HTML body is the current document with all local images converted to linked resources. Use this when sending the document as an email without writing your own MIME packaging.

Syntax
MailMessage GetEmailMessageWithLocalImagesEmbedded();
Returns

System.Net.Mail.MailMessage -- the constructed message ready to hand to SmtpClient.Send.

Example
using (MailMessage msg = htmlEditor1.Content.GetEmailMessageWithLocalImagesEmbedded())

{

    msg.From = new MailAddress("you@example.com");

    msg.To.Add("customer@example.com");

    msg.Subject = "Monthly report";

    new SmtpClient("smtp.example.com").Send(msg);

}

LoadBodyHtmlFromFile Method

Loads an HTML fragment from filePath using the given encoding and replaces the body content with it. The document head and DOCTYPE are preserved.

Syntax
void LoadBodyHtmlFromFile(string filePath, Encoding encoding);
Parameters
NameTypeDescription
filePathstringSource file path.
encodingSystem.Text.EncodingFile encoding (e.g. Encoding.UTF8).
Example
htmlEditor1.Content.LoadBodyHtmlFromFile(@"C:\templates\body.html", Encoding.UTF8);

LoadDocumentHtmlFromFile Method

Loads a complete HTML document from filePath using the given encoding and replaces the entire document.

Syntax
void LoadDocumentHtmlFromFile(string filePath, Encoding encoding);
Parameters
NameTypeDescription
filePathstringSource file path.
encodingSystem.Text.EncodingFile encoding.
Example
htmlEditor1.Content.LoadDocumentHtmlFromFile(@"C:\templates\letter.html", Encoding.UTF8);

SaveBodyHtmlToFile Method

Writes the body HTML to filePath. Existing files are overwritten.

Syntax
void SaveBodyHtmlToFile(string filePath);
Parameters
NameTypeDescription
filePathstringDestination file path.
Example
htmlEditor1.Content.SaveBodyHtmlToFile(@"C:\out\fragment.html");

SaveDocumentHtmlToFile Method

Writes the complete HTML document (DOCTYPE, head, body) to filePath.

Syntax
void SaveDocumentHtmlToFile(string filePath);
Parameters
NameTypeDescription
filePathstringDestination file path.
Example
htmlEditor1.Content.SaveDocumentHtmlToFile(@"C:\out\full.html");

SaveEditorContentAsXml Method

Serializes the document HTML as XML and writes it to the supplied file. Provided for host apps that store editor content as XML.

Syntax
void SaveEditorContentAsXml(string fileName);
Parameters
NameTypeDescription
fileNamestringDestination XML file path.
Example
htmlEditor1.Content.SaveEditorContentAsXml(@"C:\out\snapshot.xml");

OpenFile Method

Opens an HTML file from filePath and loads it into the editor. Encoding is detected automatically. Fires the editor's FileOpened event on success.

Syntax
void OpenFile(string filePath);
Parameters
NameTypeDescription
filePathstringPath to an HTML file.
Example
using (var dlg = new OpenFileDialog { Filter = "HTML files|*.html;*.htm" })

{

    if (dlg.ShowDialog() == DialogResult.OK)

        htmlEditor1.Content.OpenFile(dlg.FileName);

}

ClearContent Method

Clears the document body. The document's head, DOCTYPE, and configured base URL are preserved.

Syntax
void ClearContent();
Example
private void NewDocumentButton_Click(object sender, EventArgs e)

{

    htmlEditor1.Content.ClearContent();

}

UpdateBaseUrl Method

Updates the <base href> element of the document. Equivalent to assigning the WinFormHtmlEditor.BaseUrl property.

Syntax
void UpdateBaseUrl(string baseUrl);
Parameters
NameTypeDescription
baseUrlstringThe new base URL.
Example
htmlEditor1.Content.UpdateBaseUrl("https://cdn.example.com/assets/");

GetRightToLeft Method

Returns the document's right-to-left setting.

Syntax
RightToLeft GetRightToLeft();
Returns

System.Windows.Forms.RightToLeft -- the RTL mode (Yes, No, or Inherit).

Example
RightToLeft rtl = htmlEditor1.Content.GetRightToLeft();

Debug.WriteLine($"Current RTL mode = {rtl}");

SetRightToLeft Method

Sets the document's right-to-left direction. Use this for languages such as Arabic or Hebrew.

Syntax
void SetRightToLeft(RightToLeft rightToLeftValue);
Parameters
NameTypeDescription
rightToLeftValueSystem.Windows.Forms.RightToLeftRTL mode (Yes, No, or Inherit).
Example
htmlEditor1.Content.SetRightToLeft(RightToLeft.Yes);

ResetTableManipulator Method

Resets the table-authoring helper attached to the current document. Call this after restructuring tables programmatically so the next user interaction sees a fresh manipulator state.

Syntax
void ResetTableManipulator();
Example
htmlEditor1.Content.SetBodyHtml(rebuiltHtml);

htmlEditor1.Content.ResetTableManipulator();

Dispose Method (inherited from IDisposable)

Releases unmanaged resources held by the content service. The control disposes its services automatically when the control itself is disposed; host applications normally do not call this directly.

Syntax
void Dispose();
Example
// The host control owns disposal -- only call this if you took ownership of the service.

htmlEditor1.Content.Dispose();

TableAuthoringService Property

Gets or sets the table-authoring sub-service. The sub-service offers row/column/cell operations (insert before/after, delete, merge), zero-border guideline visibility, and selected-cell background color.

Syntax
ITableAuthoringService TableAuthoringService { get; set; }
Property value

ITableAuthoringService -- the table-authoring service.

Remarks

Common members: InsertColumn(InsertPositions), DeleteColumn(), InsertRow(InsertPositions), DeleteRow(), MergeSelectedCells(), CanMergeCells(), ShowGuidelinesForTablesWithZeroBorder(bool), HideGuidelinesOfTablesWithZeroBorder(bool), IsTableBorderZero(IHTMLElement), SelectedCellBackgroundColor, EnableTableCellMerging, GetTableManipulator(), ResetTableManipulator().

Example
var tas = htmlEditor1.Content.TableAuthoringService;

tas.InsertRow(InsertPositions.Below);

if (tas.CanMergeCells()) tas.MergeSelectedCells();

MailMerge Property

Gets the mail-merge placeholder insertion sub-service (Feature 2.5.5). The host application registers a list of PlaceholderField entries, and the editor lets the end user insert any of them as a placeholder span -- useful for building templates that are later filled per-record at send time.

Syntax
IMailMergeService MailMerge { get; }
Property value

IMailMergeService -- the mail-merge service.

Remarks

Members: IList<PlaceholderField> PlaceholderFields { get; set; } -- fields registered for end-user insertion; void InsertPlaceholder(PlaceholderField field) -- inserts a placeholder span at the caret (ignored in source-edit mode); event EventHandler<PlaceholderInsertedEventArgs> PlaceholderInserted -- fires after a span is inserted with the field and emitted HTML.

Example
htmlEditor1.Content.MailMerge.PlaceholderFields = new List<PlaceholderField>

{

    new PlaceholderField { Name = "FirstName", DisplayLabel = "First Name" },

    new PlaceholderField { Name = "OrderTotal", DisplayLabel = "Order Total" }

};

htmlEditor1.Content.MailMerge.PlaceholderInserted += (s, e) =>

    Debug.WriteLine($"Inserted {e.Field.Name}: {e.InsertedHtml}");

Remarks

The member SetAttributeValueOfAnElementFromBODY appeared in older releases but has been removed; use SetAttributeValueOfAnElement for both head and body elements. Methods that depend on a live MSHTML document require the editor to be in WYSIWYG design mode -- calls made in source-edit mode are either ignored or return last-loaded data. All calls must be made on the UI thread.

Last updated on May 14, 2026