Inserting text using Word object model

John 466 Reputation points
2023-02-19T13:31:08.0466667+00:00

How would I insert text into a Rich Text Box using the Word object model?

Here is a code snippet:


using System;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop;



namespace Plant_A_Tree
{
    public partial class Plant_Tree_Main_Interface : Form
    {
        Selection selection;

        public Plant_Tree_Main_Interface()
        {
            InitializeComponent();
        }

   
        private void Plant_Tree_Main_Interface_Load(object sender, EventArgs e)
        {
           
                



        }

        private void btnInsert_Text_Click(object sender, EventArgs e)
        {


selection = new Selection();  // This may generate an error.

            selection.InsertBefore("Hello, John!"); //This Generates an error and needs to be fixed.





        }
    }
}

Word
Word
A family of Microsoft word processing software products for creating web, email, and print documents.
842 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,906 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Olaf Helper 44,501 Reputation points
    2023-02-20T07:23:06.54+00:00

    selection.InsertBefore("Hello, John!"); //This Generates an error and needs to be fixed.

    Sure it do raise an "null reference exception", because you declare the variable "selection", but never set it, so it' null. => failure.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.