PJW
PJW

Reputation: 5417

Object Not Set to an Instance of an Object Error (resisting step through bug finding)

I have a winforms app written in c#

There is a button which generates a document from a template.

The user types a name for the new document in a textbox, and selects a business from a datagrid to address the document to.

When I click the button I get an 'Object not set to an instance error'.

Here is the event handler

private void btnCreateDocument_Click(object sender, EventArgs e)
        {
            try
            {
                #region Validation

                if (txtCreateDocName.Text.Length == 0)   //...BreakPoint here
                {
                    MessageBox.Show("Please enter a Name for your new Document", "Missing Document Name");
                    return;
                }

                if (selectedBusiness == null)
                {
                    MessageBox.Show("Please select a Contact or Business to send this Document to", "No Business Selected");
                    return;
                }

                #endregion

                DataGridViewRow row = (DataGridViewRow)dataTemplates.CurrentCell.OwningRow;

                string templatePath = row.Cells["Path"].Value.ToString();                
                string fileName = txtCreateDocName.Text;
                string caseFolder = txtFolder.Text;                
                string ourRef = currentCase.DisplayNo;
                string caseHeader = currentCase.Claimant + " -v- " + currentCase.Defendant;

                string address = selectedBusiness.Name + Environment.NewLine +
                                 selectedBusiness.Address1;
                if (selectedBusiness.Address2 != null)
                {
                    address += Environment.NewLine + selectedBusiness.Address2;
                }
                if (selectedBusiness.Address3 != null)
                {
                    address += Environment.NewLine + selectedBusiness.Address3;
                }
                address += Environment.NewLine + selectedBusiness.Region
                         + Environment.NewLine + selectedBusiness.Postcode;

                string salutation = "Dear ";
                if (selectedContact != null)
                {
                    salutation += selectedContact.Title + " " + selectedContact.FirstName + " " + selectedContact.Surname;
                }
                else
                {
                    salutation += "Sirs";
                }

                string childTable;
                int childID;
                if(selectedContact != null)
                {
                    childTable = "Contact";
                    childID = selectedContact.ID;
                }
                else
                {
                    childTable = "Business";
                    childID = selectedBusiness.ID;
                }
                int linkID = Link.LocateLink("Case", currentCase.ID, childTable, childID);
                Link l = new Link(linkID);
                string yourRef = l.Reference;

                string docPath = Document.CreateLetter(fileName, templatePath, caseFolder, address, salutation, yourRef, ourRef, caseHeader);
            }
            catch (Exception ex)
            {
                MessageBox.Show("frmCase: btnCreateDocument_Click()" + Environment.NewLine + ex.Message);
            }
        }

Now what is really perplexing is that when I set a Breakpoint on the first line of this event handler I still get the error without the Breakpoint apparently being reached?!

However, if I do NOT enter a document name in txtCreateDocName then the MessageBox warning is reached. This shows that the Event Handler is called when the button is clicked, so why the error without reaching the Breakpoint when I do enter something into txtCreateDocName.

Additional Info

This just got even stranger. Whilst running the code I tried placing / moving the breakpoint(s) and received a warning saying the source code was different to the original. I found the following thread about this. From reading through those comments, I believe this may have happened in my project because I changed the system clock in order to let me enter some historical data for testing purposes. None of the solutions in that thread work however.

Moreover, I even tried deleting all of the Validation #region including the MessageBox about entering a Document name. However when I run the code again and fail to enter a document name the message box appears on my screen, even though I have deleted it from the Code.

It is as if, there is an invisible older version of my code which is being run, rather than the current one I am looking at in VS. I would be most grateful if anyone could suggest a way to resolve this most unusual bug.

This Got More Serious

I decided to put down the part of the application I was working on for a while, and made significant changes to another Form. However when I run the application, NONE of the changes I have made take effect. So in Visual Studio I am looking at one solution with all my new controls and code, but at runtime I seem to be getting the 'previous' unaltered solution.

Please can anyone help me resolve this, as it looks like undermining months of work.

Upvotes: 0

Views: 704

Answers (2)

PJW
PJW

Reputation: 5417

I was finally able to resolve this after speaking to a friend who has worked in software for a long time. The solution, not entirely unsurprisingly, was simple in the end.

The error had started when I had changed the system clock to enter some historical data. What really messed things up is I also changed the clock forwards (into the future). It appears that this meant there was a mismatch between the date stamp on the application dll and the modules in VS. Rebuilding through the Debug menu was not working, because the dll had a newer date than the modules in VS, hence it saw nothing to update.

The solution was to manually delete everything in the bin folder giving VS nothing to run and forcing it to rebuild the application from scratch. Now everything works as it should again, and what a relief that is.

Hope this might help someone else one day.

Upvotes: 1

quetzalcoatl
quetzalcoatl

Reputation: 33546

Do you have any 'keypress' handlers or 'textchange' validators on that Text Control? Maybe it's them who throws. When you "not write anything" in the control, no keypresses and no validation occurs - so the ButtonClick is invoked. However, if any change is made to the text, then the Text Control will fire the change handlers at the moment of LOSING THE FOCUS, so immediatelly after you "Click" but before the focus is moved to button and before button notices the click. This way, if the text-change handler throws, an exception will be thrown as if "when you click" but no buttonclick handler will fire. Try entering the same text in that control and then DONT click - press TAB or ENTER so that it loses focus. If an exception occurs, then it's surely the change handler (or keylistener, or Binding parser, or .... - I dont know what you have there).

Also, have you checked the StackTrace of that exception that is thrown? It will show you exactly which method has thrown.

Finally, you can go to Debug menu, into Exceptions and find System.NullReferenceException and mark it as "when thrown". Now the VS will automatically BREAK whenever this exception is thrown and it will instantly jump to the place of code that throws it. This way you will see immediatelly the culprit. Don't forget to uncheck that option later.

Upvotes: 0

Related Questions