Reputation: 1697
I am developping a .Net console application which creates a Word document.
My Visual Studio project has a reference to the Microsoft.Office.Interop.Word assembly.
I want to create a table cell.
I want to write two lines of text in the cell.
The first line must be bold.
Here is my code :
l_table = l_range.Tables.Add(l_range, 1, 1);
l_table.Borders.Enable = 0;
l_table.Rows.AllowBreakAcrossPages = 0;
l_cellRange = l_table.Cell(1, 1).Range;
l_cellRange.Text = "First Line";
l_cellRange.Bold = 1;
l_cellRange.InsertParagraphAfter();
l_cellRange.Collapse(WdCollapseDirection.wdCollapseEnd);
l_cellRange.Text = "Second Line";
l_cellRange.Bold = 1;
The following code line raises an exception : l_cellRange.Text = "Second Line";
The exception message (Translation from French to English) : Unvalid action at end of line
Can someone explain me what is wrong with my code ?
Upvotes: 1
Views: 4014
Reputation: 96
You are missing a call to Range.MoveEnd()
.
Per the MSDN documentation on Range.InsertParagraphAfter, the Range expands to include the new paragraph when you insert a paragraph.
Then, when you collapse the range, which already includes the new paragraph, you are moving the range's start and end positions to after the ending paragraph mark. MSDN's article on Range.Collapse specifically mentions this effect and how to fix it.
In short, you need to insert MoveEnd()
after your call to Collapse()
:
l_cellRange.Collapse(WdCollapseDirection.wdCollapseEnd);
l_cellRange.MoveEnd(WdUnits.wdCharacter, -1);
l_cellRange.Text = "Second Line";
This will move the range start and end positions to just before the end paragraph mark and allow you to insert text as expected.
Having said all that, I agree with kape123. Generating the document via XML is the more sustainable way to go.
Upvotes: 4