RemoveText and tabs

Oct 10, 2009 at 5:03 AM

I'm experimenting with DocX and love the simplicity and power, but have hit a roadblock. I'm trying to overwrite a document paragraph by paragraph in a simple loop that uses the following on each:

.RemoveText(0, False)

.Append(NewText)

This works fine, except when a paragraph contains internal tabs, and then I get an "object not instantiated" error on the RemoveText call. Is there a fix for this?

Coordinator
Oct 10, 2009 at 4:18 PM
Hello RWalker,
 
Remove should have no problem with internal tabs, you may have found a bug. 

I have a quick solution for you. You could remove the paragraphs instead of removing the text in the paragraphs. Try the below code out and let me know if it works for you.

kind regards and happy coding,
Cathal
 
// Load a document.
using(DocX document = DocX.Load("Test.docx"))
{
    // Loop through the Paragraphs in this document.
    for(int i = 0; i < document.Paragraphs.Count(); i++)
    {
        // Get Paragraph p.
        Paragraph p = document.Paragraphs[i];
        
        // Insert a Paragraph to replace p.
        Paragraph replacement = p.InsertParagraphAfterSelf("");
        replacement.Append(string.Format("Replacement for Paragraph {0}", i));
        
        // Remove Paragraph p.
        p.Remove(false);
    }

    // Save all changes made to this document.
    document.Save();
} // Release the document from memory.
Feb 8, 2013 at 5:00 AM
Another Solution:

Remove the tabs and then remove the text.

XNamespace ns = docxObject.Xml.Name.Namespace;
Paragraph p = document.Paragraphs[0];
p.Xml.Descendants().Elements(ns + "tabs").Remove();
p.First.RemoveText(0, false);