1
votes

I am trying to insert a paragraph with a heading and some text into a word document.

Everything works fine except when I apply the heading style it changes the style of the following text, or, when I change the paragraph body back to "Normal" it changes the heading back to plain text. I cannot get word to recognize them as separate paragraphs, obviously I am doing something very wrong but I just cannot see what. Actual code is attached:-

Word.Paragraph p2 = wD.Paragraphs.Add(R.End);
Word.Range r2 = p2.Range;
r2.InsertAfter("If any updates were made then link to  the follow on program "
        + curTarget.followOn + ".\n");
string style = "Normal";
object objStyle = style;
r2.set_Style(ref objStyle);
r2.InsertParagraphAfter();
Word.Paragraph p3 = wD.Paragraphs.Add(r2);
Word.Range r3 = p3.Range;
r3.Text = "Call follow on process.\n";
style = "Heading 4";
objStyle = style;
r3.set_Style(ref objStyle);
r2.InsertParagraphAfter();

Apologies for the messy code but its been re(de)-factored about twenty times.

1
Hmm, actually this code is looking like J# rather than C#, just based on the set_Style syntax. Could that be part of the confusion?Paul Bellora

1 Answers

3
votes

As I noted in the comment, some of your code looks suspiciously like J# rather than C#. Not sure how much if at all that's contributing to the confusion.

I notice Word.Range.set_Style is taking a ref argument. And I notice the reference you pass in is the same variable, which you reassign in between calls to set_Style:

string style = "Normal";
object objStyle = style;
r2.set_Style(ref objStyle);
...
style = "Heading 4";
objStyle = style;
r3.set_Style(ref objStyle);

Instead, try redeclaring a new variable for the second style:

string style = "Normal";
object objStyle = style;
r2.set_Style(ref objStyle);
...
string style2 = "Heading 4";
object objStyle2 = style2;
r3.set_Style(ref objStyle2);

In all honesty, this is a wild guess - the use of ref and the reassignment shouldn't matter here, at least in C#, but it did raise a flag when I looked over your code.

If the code is in fact J#, it's possible that the use of ref is causing alternate behavior that results in your issue - I wasn't able to find enough J# documentation to prove or refute this theory though.