Getting error when trying to clear bookmark from table row

I am using a bookmark to find a specific table/table row, which I then clone one or more times to fill with data and then add to the parent table. I want to remove the bookmarks from the newly added rows, but keep the bookmark on the original row that was cloned. After inserting the new row into the table, I am attempting to clear the bookmarks. However, when I clone, fill, and add a new row again, an error is thrown that says that it can’t find the bookmark. When I inspect the properties of the second new row during debug, the range does contain the bookmark that it claims it can’t find, though I am not actually trying to call the bookmark by name. How can I clear this bookmark from all newly added cells?

Bookmark bkmrk = doc.Range.Bookmarks["tablebookmark"];
Node node = bkmrk.BookmarkStart.ParentNode;
Cell cell = (Cell)node.ParentNode;
Row rowOrig = (Row)cell.ParentRow;
List<TesTDaTa> dat = TestCollection.LoadCollection();
foreach (TesTDaTa t in dat)
    Row tRow = (Row)rowOrig.Clone(true);
    foreach (Cell c in tRow.Cells)
        string fldName = FindFieldNameFromText(c.Range.Text);
        var props = (from p in t.GetType().GetProperties() where p.Name == fldName select p);
        if (props.Count() > 0)
            c.Range.Replace(fldName, t.GetType().GetProperty(fldName).GetValue(t, null).ToString(), false, false);
    if (tRow.Range.Bookmarks.Count > 0)

This message was posted using Aspose.Live 2 Forum

Sorry. I figured out a way around the error. I decided to insert the rows before the “original” row and then just remove the BookMarkStart from the newly inserted row. I am curious to know, however, how I would do it if I needed to append the new rows to the end of the table. Is that possible?

Hi Malieka,
Thanks for your inquiry.
I was unable to reproduce the issue of an exception being thrown using your code simplfied a little, but I was however able to reproduce the original bookmark being removed too.
The reason this sort of behaviour happens is because the two bookmarks have the same name. The Bookmark class is a facade which allows access to the BookmarkStart and BookmarkEnd nodes. If there are two bookmarks with the same name then it can get confused.
To avoid these issues you are experiencing I suggest you replace the call to tRow.Range.Bookmarks.Clear() with a more direct method of removing the bookmark nodes:

tRow.GetChildNodes(NodeType.BookmarkStart, true).Clear();
tRow.GetChildNodes(NodeType.BookmarkEnd, true).Clear();

Also please note, from the looks of what you are doing in your code example, using Mail merge with regions instead would achieve what you are looking to do much more easily.

The Mail Merge functionality would be hard to implement in this current project, but I will try this. Thank you.