I spent 2 hours trying to figure out why a form I was working on was telling me that there was something wrong with a control in the designer and that is why the form wouldn’t render. I was getting the dreaded “Object reference not set to an instance of an object” error. It wasn’t believable because all of the code in the designer was fine. I have seen this error countless times and each time it is for something that will give you a head palm moment. You might not want to believe this, but you – the programmer – are definitely at fault when this happens. It turns out that code in a file that wasn’t even part of the windows form was attempting to use an object before it was instantiated. Thus head palm moment and it was my co-workers fault because I didn’t write the code :D.
I am going to try to generalize the steps to take to fix the problem.
- Don’t get angry, calm down, go get some coffee or watch a YouTube video for about 5 minutes. Avoid getting pissed off when dealing with these frustrating issues because it isn’t going to help.
- Avoid editing the Designer File directly, chances are that is NOT where the problem is. If your problem is the Designer file then there is something really messed up and the only way to fix it really is to blow away the whole form and start from scratch, but only do that in a last resort scenario.
- If you can run your code then this is an indication that it probably isn’t the form itself or the controls on the form. Your problem lies somewhere in the actual thicket of your code.
- You are looking for a place where an object is being used un-instantiated just like the error tells you. The bad news is that the compiler might not tell you exactly where this is happening.
- Time for you to start debugging your code. If you can walk your code that is a good sign, because at least it gives you a chance to find out where the problem is occurring.
- If you are getting an error like this one: “Exception has been thrown by the target of an invocation” then this means that an exception is being thrown by something that has been invoked such as a proxy call or an event. Those are harder to debug, but it all comes down to the same thing:
- You need to wrap the code that you suspect is throwing the exception in a try/catch block and inspect the exception.
- After capturing the exception look at the stack trace and find out who the culprit is.
- More often than not this will find you the un-initialized object.