I was trying to do a Word Document Editor in c# with the main idea of changing certain fields in a word document. Like for example where the word name, to replace with an actual name that I type in a windows form field. Think of it as a Certificate generator. where i just need to change the Date and name.
But i keep getting an error where the Object reference not set to an instance of an object.
The error im getting is on Word.Range nom = ObjDoc.Bookmarks.get_Item(ref name1).Range;
here is the complete code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object ObjMiss = System.Reflection.Missing.Value;
Word.Application ObjWord = new Word.Application();
string route = Application.StartupPath @"C:\document.docx";
object parametro = route;
object name1 = "name";
object telephone1 = "telephone";
Word.Document ObjDoc = ObjWord.Documents.Open(parametro , ObjMiss);
Word.Range nom = ObjDoc.Bookmarks.get_Item(ref name1).Range;
nam.Text = textBox1.Text;
Word.Range tel = ObjDoc.Bookmarks.get_Item(ref telephone1).Range;
tel.Text = textBox2.Text;
object rango1 = nam;
object range2 = tel;
ObjDoc.Bookmarks.Add("name", ref range1);
ObjDoc.Bookmarks.Add("telephone", ref range2);
ObjWord.Visible = true;
}
}
}
I am completely sure I have the correct route the word document, I also inserted the bookmarks necesary in the place I want to replace the words.
CodePudding user response:
Are you sure that
Application.StartupPath @"C:\document.docx";
yelds the intended path? It would be something like
"C:\path\to\application\C:\document.docx"
As far as I know, " : " is not even an accepted character for folder names.