tags:

views:

386

answers:

1

Hi.

I'm currenty trying some new things with OpenXml but I recently came across some trouble. As the title says I'm trying to insert data dynamically into a table using Xml. To indentify the table in my Worddoc I've put a Rich Text Content Control arround it.

Everything worked & looked fine until I tried to search my document for the tagname of the Rich Text Content Control. I keep getting a "Object reference not set to an instance of an object." while running my code.

He's the line where it happens:

SdtBlock ccWithTable = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == t.Name).Single();

I've used following MSDN document to try and achieve my goal, without succes:

Inserting Repeating Data Items into a Word 2007 Table by Using the Open Xml API

If anyone can help me, I would love you long time.

+1  A: 

Okay, I've created a workarround which actually works even better.

First I retrieve all the tables from the document..

List<Table> tables = mainPart.Document.Body.Descendants<Table>().ToList();

Then I check the tag-parameter of SdtBlock which is the parent of my Table, to see if they match.

for (int f = 0; f < tables.Count; f++)
 {
   // If a table is found in the correct Content Control, fill it up with the data
   if (tables.ElementAt(f).Parent.Parent.GetFirstChild<SdtProperties>().GetFirstChild<Tag>().Val == t.Name)
     { //the rest of your code...

t.Name is the tag of the content I wanted to find.

I'm actually pretty pleased about this result because this solves the fact that several same tables (in the same document, with the same tag) could not be filled.

Small sidenote: It might be best to try catch the if, if you have other tables in your document which aren't dynamic.

tables.ElementAt(f).Parent.Parent.GetFirstChild<SdtProperties>().GetFirstChild<Tag>().Val 

would kill those.

J. Vermeire