5

I am trying to insert text into the word document. But whenever i execute my code the text enter by me in the text box is always added in the beginning. I am unable to insert the text in the end of the document. I am unable to fix this using Range also.

private void button2_Click(object sender, EventArgs e) { try { if (textBox1.Text != "") { Microsoft.Office.Interop.Word._Application oWord; object oMissing = Type.Missing; oWord = new Microsoft.Office.Interop.Word.Application(); oWord.Visible = false; oWord.Documents.Open(filePath); oWord.Selection.TypeText(textBox1.Text); oWord.ActiveDocument.Save(); oWord.Quit(); MessageBox.Show("The text is inserted."); textBox1.Text = ""; } else { MessageBox.Show("Please give some text in the text box"); } } catch(Exception) { MessageBox.Show("Please right click on the window and provide the path"); } } 
3
  • 1
    Did you try with InsertAfter? Commented Sep 21, 2015 at 11:08
  • Move to the end of the document with these two commands: ActiveDocument.Characters.Last.Select then Selection.Collapse Commented Sep 21, 2015 at 11:11
  • Thanks..!!! ActiveDocument.Characters.Last.Select and Selection.Collapse comments works..!!! Commented Sep 21, 2015 at 11:16

2 Answers 2

5

Line 1 and Line 2 in the below code helps me. The following code works fine.

private void button2_Click(object sender, EventArgs e) { try { if (textBox1.Text != "") { Microsoft.Office.Interop.Word._Application oWord; object oMissing = Type.Missing; oWord = new Microsoft.Office.Interop.Word.Application(); oWord.Visible = false; oWord.Documents.Open(filePath); oWord.ActiveDocument.Characters.Last.Select(); // Line 1 oWord.Selection.Collapse(); // Line 2 oWord.Selection.TypeText(textBox1.Text); oWord.ActiveDocument.Save(); oWord.Quit(); MessageBox.Show("The text is inserted."); textBox1.Text = ""; } else { MessageBox.Show("Please give some text in the text box"); } } catch(Exception) { MessageBox.Show("Please right click on the window and provide the path"); } } 
Sign up to request clarification or add additional context in comments.

Comments

-2

You have to use append method to add the text within the same line rather than entering in next line Ex:

File.AppendAllText(@"c:\path\file.txt", textBox1.Text); 

This might help

2 Comments

He is working with a word object and not a simple text file.
I just tried to explain the use of append method using this example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.