Replicating/cloning rows

Nov 17, 2011 at 4:48 PM

Hi,

How can I do to replicate/clone a table row in order to insert it several times (with some text replaced) in the same table?

Thanks in advance.

Regards,

Germán.

Developer
Nov 17, 2011 at 5:44 PM

Hi, gschuager.

If I understood you correctly, It is impossible now. But if you write the code (how you see this functionality and want to use it), I will help and try do it.

Nov 17, 2011 at 6:12 PM

Thanks DragonFire,

I have a table with 2 rows: the first one is the header and the 2nd is a "template row" which I need to repeat replacing some placeholder text with meaningful data.

In pseudo-code it would be something like this:

 

var templateRow = table.Rows.Last();
foreach (var currentRecord in records)
{
   // the following overload doesnt exist and would create a new row
   // with the same contents as the row passed as parameter
   var newRow = table.InsertRow(templateRow); 

   // this method would call ReplaceText on newRow as required
   ReplacePlaceHolders(newRow, currentRecord);
}

table.RemoveRow(templateRow);

 

 

I already have something that works but it is very "hacky".

I use this code to clone the template row:

var internalRowCtor = typeof (Row).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).Single();
var list = templateRow.Cells.Select(cell => CloneElement(cell.Xml)).ToList();
var newRow = (Row)internalRowCtor.Invoke(new object[]
				                        {
				                            templateTable, templateDoc,
				                            new XElement(XName.Get("tr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"), list)
				                        });

then do the replacement thing and then this other snippet to add it at the end of the table:

templateTable.Rows.Last().Xml.AddAfterSelf(newRow.Xml);

Any help would be very welcomed.

Developer
Nov 17, 2011 at 7:25 PM

Try to update your version and use a new Table.InsertRow(Row row) method....

Nov 17, 2011 at 8:14 PM

It doesn't work as it is (I get all rows with the same content, corresponding to the first one that I replaced), but changing this:

Row newRow = new Row(this, Document, row.Xml);

by this:

var list = row.Cells.Select(cell => HelperFunctions.CloneElement(cell.Xml)).ToList();
Row newRow = new Row(this, Document, new XElement(XName.Get("tr", DocX.w.NamespaceName), list));

then it works correctly.

Thank you very much.

Developer
Nov 18, 2011 at 7:58 AM

Yes, of course you are right.

Try to use it one more time =) 

Nov 18, 2011 at 10:43 AM

Great!

Thank you again.

Developer
Nov 18, 2011 at 11:06 AM

You are welcome =)

But If you have a one free minute, I will be glad if you show mistakes in my posts =) Becouse now I try to study English seriously...

Nov 18, 2011 at 12:18 PM

Sorry but I'm not a native english speaker either :)

Developer
Nov 19, 2011 at 12:26 PM

Okey =)