Trying to end Table results in error

I am creating a Table programmatically using DocBuilder.StartTable() to create the table, then creating row and cell objects and populating them with content as needed and using table.AppendChild(row) and row.AppendChild(cell) to build up the table. At the end I use DocBuilder.EndTable() to close out the table and continue on with my document. This works as long as I don’t have any content inserted into the cells using DocBuilder.Write() . If I create paragraph object, then create runs and append them to the the paragraph and append the paragraph to the cells, everything works well even with complicated tables.

However, if I try to write content using DocBuilder.Write to get content into a cell, I get the error “Cannot end a table while not building a table.” when calling DocBuilder.EndTable(). It seems like my calls to DocBuilder.Write cause the DocBuilder to lose the context of the table and fail. I even try to get back into the context of the Table with code like:

this.wordDocBuilder.MoveTo(theTable);
this.wordDocBuilder.EndTable();

but I get the same error. I would like to avoid using the DocBuilder to insert content into the tables if at all possible, but some content requires a Word Field to be inserted. Is there any way to create Word Field object and append it to a run, or do I have to use DocBuilder.InsertField()?

If I have to use DocBuilder.InsertField(), how can I ensure that it occurs within the context of the table so that the field appears in the table cell as expected, and the EndTable() call doesn’t throw an error?

@mhimlin please use the following code snippet to insert a field into a table cell:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table1 = builder.StartTable();
builder.InsertCell();
builder.InsertField(Aspose.Words.Fields.FieldType.FieldAuthor, true);
builder.EndRow();
builder.EndTable();

doc.Save("C:\\Temp\\output.docx");

If you need to add rows and cells to the table using the AppendChild method, please follow the approach shown in the code snippet below:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table1 = builder.StartTable();
builder.EndTable();

Row row = new Row(doc);
table1.AppendChild(row);

Cell cell1 = new Cell(doc);
Cell cell2 = new Cell(doc);
row.AppendChild(cell1);
row.AppendChild(cell2);

builder.MoveToCell(0, 0, 0, 0);
builder.Writeln("test");

builder.MoveToCell(0, 0, 1, 0);
builder.InsertField(Aspose.Words.Fields.FieldType.FieldAuthor, true);

output.docx (7.2 KB)