Click here to Skip to main content
15,886,833 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
error message; nullreferenceecxeption was unhandled

Form 1 code (here the user fills in a form with his information)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Form_NieuweAanvraag
{

    public partial class Form_NieuweAanvraag : Form
    {
        private string naam, voornaam, adres, gemeente, postcode, startdatum, deeltijds;
        public static string passingText;
    
        public Form_NieuweAanvraag()
        {
            InitializeComponent();
        }

       
        private void btn_Reset_Click(object sender, EventArgs e)
        {

            ClearTextBoxes(this.Controls);
            rbtnJongen.Checked = false;
            rbtnMeisje.Checked = false;
        }

        private void ClearTextBoxes(Control.ControlCollection ctrlCollection)
        {
            foreach (Control ctrl in ctrlCollection)
            {
                if (ctrl is TextBoxBase)
                {
                    ctrl.Text = String.Empty;
                }
                else
                {
                    ClearTextBoxes(ctrl.Controls);
                }
            }
        }

        public void btn_Convert_Click(object sender, EventArgs e)
        {



            if (String.IsNullOrEmpty(txtNaam.Text))
            {
                MessageBox.Show("Gelieve het formulier correct in te vullen.", "INFANO - FOUT", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            { 
            naam = txtNaam.Text;
            voornaam = txtVoornaam.Text;
            adres = txtAdres.Text;
            gemeente = txtGemeente.Text;
            postcode = txtPostcode.Text;
            startdatum = txtStartdatum.Text;
            deeltijds = txtDeeltijds.Text;

            //nieuwe instantie van mijn tweede form maken
            Form_Contract formulier = new Form_Contract(naam, voornaam, adres, gemeente, postcode, startdatum, deeltijds);
            formulier.Show();
            this.Hide();//dit huidige form start wordt verborgen


            }
        }
    }
}


error message; nullreferenceecxeption was unhandled


Form 1 code (here the user fills in a form with his information)


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Form_NieuweAanvraag
{

    public partial class Form_NieuweAanvraag : Form
    {
        private string naam, voornaam, adres, gemeente, postcode, startdatum, deeltijds;
        public static string passingText;
    
        public Form_NieuweAanvraag()
        {
            InitializeComponent();
        }

       
        private void btn_Reset_Click(object sender, EventArgs e)
        {

            ClearTextBoxes(this.Controls);
            rbtnJongen.Checked = false;
            rbtnMeisje.Checked = false;
        }

        private void ClearTextBoxes(Control.ControlCollection ctrlCollection)
        {
            foreach (Control ctrl in ctrlCollection)
            {
                if (ctrl is TextBoxBase)
                {
                    ctrl.Text = String.Empty;
                }
                else
                {
                    ClearTextBoxes(ctrl.Controls);
                }
            }
        }

        public void btn_Convert_Click(object sender, EventArgs e)
        {



            if (String.IsNullOrEmpty(txtNaam.Text))
            {
                MessageBox.Show("Gelieve het formulier correct in te vullen.", "INFANO - FOUT", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            { 
            naam = txtNaam.Text;
            voornaam = txtVoornaam.Text;
            adres = txtAdres.Text;
            gemeente = txtGemeente.Text;
            postcode = txtPostcode.Text;
            startdatum = txtStartdatum.Text;
            deeltijds = txtDeeltijds.Text;

            //nieuwe instantie van mijn tweede form maken
            Form_Contract formulier = new Form_Contract(naam, voornaam, adres, gemeente, postcode, startdatum, deeltijds);
            formulier.Show();
            this.Hide();//dit huidige form start wordt verborgen


            }
        }
    }
}
<big>Form 2 code (here the user sees a personalized version and has the button "maak document" which edits a word document to match with the given information</big>
<pre><pre>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using word = Microsoft.Office.Interop.Word;

namespace Form_NieuweAanvraag
{
    public partial class Form_Contract : Form
    {
        string naam, voornaam, adres, gemeente, startdatum, postcode, deeltijds;
        public Form_Contract(string naam, string voornaam, string adres, string gemeente, string postcode, string startdatum, string deeltijds)
        {
            
            InitializeComponent();
            this.naam = naam;
            this.voornaam = voornaam;
            this.adres = adres;
            this.gemeente = gemeente;
            this.postcode = postcode;
            this.startdatum = startdatum;
            this.deeltijds = deeltijds;

            label1.Text = "Tussen" + Environment.NewLine + "\t \t \t \t Infano VZW" + Environment.NewLine + "\t \t \t \t Keizerstraat 35" + Environment.NewLine + "\t \t \t \t 1740 Ternat" + Environment.NewLine + Environment.NewLine + "en " + Environment.NewLine + "\t \t \t \t" + naam + " "+ voornaam + Environment.NewLine + "\t \t \t \t" + adres + Environment.NewLine + "\t \t \t \t" + postcode + " " + gemeente ;

            listBox1.Text = "hierna genoemd de werknemer, is overeengekomen wat volgt:" + Environment.NewLine + Environment.NewLine;

            listBox1.Text+="Artikel 1" + Environment.NewLine;
            listBox1.Text+="De werkgever neemt de werknemer voor  tijd in dienst vanaf " + startdatum + " als regio coordinator . Evenwel kan de werknemer, wanneer de noodzaak zich voordoet, overeenkomstig de bepalingen van het arbeidsreglement, een andere taak vervullen, dan die welke met zijn beroepsbekwaamheid overeenkomt, o.a.: opdrachten die rechtstreeks of onrechtstreeks met de doelstelling van de vzw verband houden." + Environment.NewLine;

            listBox1.Text += "Artikel 2" + Environment.NewLine;
            listBox1.Text += "Deze arbeidsovereenkomst is er één voor " + deeltijds.ToLower() + "e " + " arbeid." + Environment.NewLine;

            listBox1.Text += "Artikel 3" + Environment.NewLine;
            listBox1.Text += Environment.NewLine;

            listBox1.Text += "Artikel 4" + Environment.NewLine;
            listBox1.Text += "Met het oog op de veiligheid en de gezondheid bij de arbeid is de werknemer verplicht alle voorzorgsmaatregelen opgenomen in het arbeidsreglement of zoals beschreven in de dienstnota’s in acht te nemen." + Environment.NewLine;

            listBox1.Text += "Artikel 5" + Environment.NewLine;
            listBox1.Text += "De uitvoering van de arbeidsovereenkomst kan alleen worden geschorst om de redenen en volgens de voorschriften bepaald in de wet van 3 juli 1978 op de arbeidsovereenkomsten en in het arbeidsreglement." + Environment.NewLine;

            listBox1.Text += "Artikel 6" + Environment.NewLine;
            listBox1.Text += "De wettelijke bepalingen omtrent het beëindigen van de arbeidsovereenkomst en de opzegtermijnen zijn van toepassing." + Environment.NewLine;

            listBox1.Text += "Artikel 7" + Environment.NewLine;
            listBox1.Text += "De werknemer verklaart hierbij dat hij een afschrift van het arbeidsreglement, de vertrouwelijkheidsreglement, social media en IT-policy heeft ontvangen en dat hij alle bepalingen ervan, die op heden van kracht zijn, aanvaardt." + Environment.NewLine;

            listBox1.Text += "Artikel 8" + Environment.NewLine;
            listBox1.Text += "Essentiële bestanddelen van deze arbeidsovereenkomst zijn: het loon, het recht op maaltijdcheques, gratis hospitalisatieverzekering voor het personeelslid na een jaar en de aard van de te verrichten arbeid en de arbeidstijd. De arbeidsplaats maakt geen deel uit van de essentiële arbeidsvoorwaarden. De partijen verklaren dat alle niet hiervoor opgesomde bestanddelen van de arbeidsovereenkomst bijkomstig zijn. De werkgever behoudt zich het recht voor om deze bijkomstige bestanddelen op elk ogenblik eenzijdig te wijzigen." + Environment.NewLine;

            listBox1.Text += "Artikel 9" + Environment.NewLine;
            listBox1.Text += "Partijen verklaren bij de onderhandelingen gesprekken te hebben gevoerd omtrent de verworven beroepsanciënniteit van de werknemer bij vorige werkgevers. De werknemer verklaart uitdrukkelijk dat hij/zij een beroepsanciënniteit heeft verworven bij een gelijkaardige instelling gelijk aan 0 jaar. Hij/zij aanvaardt uitdrukkelijk dat een anciënniteit van 0 jaar in aanmerking wordt genomen bij de uitvoering van de arbeidsovereenkomst vanaf de vierde maand, en hij/zij doet uitdrukkelijk afstand van het inroepen van een andere in aanmerking te nemen anciënniteit." + Environment.NewLine;

            listBox1.Text += "Artikel 10" + Environment.NewLine;
            listBox1.Text += "Alle realisaties, creaties of ontwerpen van welke aard ook gerealiseerd in het kader van de arbeidsovereenkomst, komen zonder beperking toe aan de werkgever. De werknemer draagt uitdrukkelijk alle rechten m.b.t. deze realisaties over aan de werkgever. De werkgever beslist autonoom en onbeperkt over de reproductie, exploitatie en iedere vorm van aanwending van de genoemde realisaties." + Environment.NewLine;

            listBox1.Text += "Artikel 11" + Environment.NewLine;
            listBox1.Text += "Bovendien is nog uitdrukkelijk overeengekomen: het personeelslid heeft recht op maaltijdcheques ten bedrage van € 4 per gepresteerde dag (a rato van 7,36 u/d en werknemersbijdrage inbegrepen)." + Environment.NewLine;

            listBox1.Text += "Artikel 12" + Environment.NewLine;
            listBox1.Text += "Aangezien de werknemer een leidinggevende functie bekleedt in de zin van het K.B. van 10/2/1965 tot aanwijzing van de personen die met een leidinggevende functie of met een vertrouwenspost zijn bekleedt, zal de werknemer elke bijkomende prestatie buiten de vermelde uurroosters uitvoeren, vereist in het kader van zijn verantwoordelijkheden. " + Environment.NewLine;
            listBox1.Text += "De werknemer erkent en aanvaardt dat de verloning voor deze bijkomende prestaties is inbegrepen in het tussen beide partijen overeengekomen salarispakket voorzien in artikel 4 van deze overeenkomst. Bijgevolg zal voor deze bijkomende prestaties geen enkele supplementaire bezoldiging, geen betaling van overuren en geen toekenning van enige inhaalrust verschuldigd zijn." + Environment.NewLine + Environment.NewLine;

            listBox1.Text += "Deze arbeidsovereenkomst werd opgemaakt in twee exemplaren, te Ternat, op  " + startdatum + ". Elke partij erkent het zijne ontvangen te hebben." + Environment.NewLine + Environment.NewLine;
            listBox1.Text += "Handtekening van de werknemer, \t \t \t Handtekening van de werkgever," + Environment.NewLine;

        }

        private void btnMaakDocument_Click(object sender, EventArgs e)
        {
            createworddocument(@"C:\Users\StagiairIT\Downloads\STAGE\Form_NieuweAanvraag\ContractInfanoVZW", @"C:\Users\StagiairIT\Downloads\STAGE\Form_NieuweAanvraag\Form_NieuweAanvraag\AangemaaktDocument");
        }
        private void findandreplace(word.Application wordapp, object tofindtext, object replacewithtext)
        {
            object matchcase = true;
            object matchwholeword = true;
            object matchwildcards = false;
            object matchsoundlike = false;
            object nmatchallforms = false;
            object forward = true;
            object format = false;
            object matchkashida = false;
            object matchdiactitics = false;
            object matchalefhamza = false;
            object matchcontrol = false;
            object read_only = false;
            object visible = true;
            object replace = 2;
            object wrap = 1;

            wordapp.Selection.Find.Execute(ref tofindtext,
                ref matchcase, ref matchwholeword, ref matchwildcards, ref matchsoundlike, ref nmatchallforms,
                ref forward, ref wrap, ref format, ref replacewithtext,
                ref replace, ref matchkashida, ref matchdiactitics, ref matchalefhamza, ref matchcontrol);
        }
        private void createworddocument(object contract, object saveas)
        {
            word.Application wordapp = new word.Application();
            object missing = Missing.Value;
            word.Document myworddoc = null;

            if (File.Exists((string)contract))
            {
                object readOnly = false;
                object isvisible = false;
                wordapp.Visible = false;

                myworddoc = wordapp.Documents.Open(ref contract, ref missing, ref readOnly, ref missing, ref missing, ref missing
                    , ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing
                    , ref missing, ref missing);

                myworddoc.Activate();

                

                this.findandreplace(wordapp, "<naam>", naam);
                this.findandreplace(wordapp, "<voornaam>", voornaam);
                this.findandreplace(wordapp, "<deeltijds>", deeltijds);
                this.findandreplace(wordapp, "<postcode>", postcode);
                this.findandreplace(wordapp, "<gemeente>", gemeente);
                this.findandreplace(wordapp, "<startdatum>", startdatum);
                this.findandreplace(wordapp, "<adres>", adres);
            }
            else
            {
                MessageBox.Show("Fout opgetreden bij maken bestand.", "INFANO - FOUT", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            myworddoc.SaveAs2(ref saveas, ref missing, ref missing, ref missing
                    , ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing
                    , ref missing, ref missing, ref missing, ref missing, ref missing);

            myworddoc.Close();
            wordapp.Quit();
            MessageBox.Show("Het bestand is gemaakt", "INFANO - MELDING", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}


they refer to

wordapp.Selection.Find.Execute(ref tofindtext, ref matchcase, ref matchwholeword, ref matchwildcards, ref matchsoundlike, ref nmatchallforms, ref forward, ref wrap, ref format, ref replacewithtext, ref replace, ref matchkashida, ref matchdiactitics, ref matchalefhamza, ref matchcontrol); }

when I get an error, even tough this looks just fine. I couldn't find an answer online so I created an account. Thanks for helping out.

What I have tried:

Watch youtube video and read guides
Posted
Updated 18-Feb-22 6:05am

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Comments
Member 15539627 18-Feb-22 5:24am    
Thanks for your comment. But I don' understand, I showed all of my code right? I have never used this method before so I dont understand what I'm doing wrong and what I should do to fix it. Kind regards
OriginalGriff 18-Feb-22 5:36am    
The problem is that we can;t run your code with your data on your system - so we can;t point at a bit of code that fails and say "it's that bit" - but you can.

You know how to use the debugger (or Google will show you how) so start using it. It will show you the line the exception happened on together with the data that caused the exception, and you can start working back from there.
We can't do that for you!
The error refers to objects not found in your document. They might be contained within frames or shapes which you then need to refer to first -

1. Use your code to replace the text that does not belong to frames.
2. Use wordApp.Selection.Document.Shapes to get the list of shapes.
3. Make a loop for all of the shapes. For each shape, get the shape.TextFrame.TextRange property.
4. For the got ranges, call range.Find.Execute.

The below code might put you in the right direction -
public void FindReplace(List<repvals> replaceVals, string docLocation, int listLen)
        {

            //Opens a new Word application
            var app = new Microsoft.Office.Interop.Word.Application();
            //Opens the .docx
            var doc = app.Documents.Open(docLocation, true, false);

            //Selects the document
            var range = doc.Range();

            for (int i = 0; i < listLen; i++)
            {

                //Finds the parameter, then replaces
                range.Find.Execute(FindText: Convert.ToString(replaceVals[i].tempVal), Replace: WdReplace.wdReplaceAll, ReplaceWith: Convert.ToString(replaceVals[i].Boxes));

                var shapes = doc.Shapes;
                //Finds text within textboxes, then changes them
                foreach (Microsoft.Office.Interop.Word.Shape shape in shapes)
                {
                    var initialText = shape.TextFrame.TextRange.Text;
                    var resultingText = initialText.Replace(Convert.ToString(replaceVals[i].tempVal), Convert.ToString(replaceVals[i].Boxes));
                    shape.TextFrame.TextRange.Text = resultingText;
                }

            }
            //prints document
            doc.Save();
            doc.Close();

            //fully closes Word
            Marshal.ReleaseComObject(app);
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900