This was a more puzzling error that I have had to deal with in a long time. Every time I started up my windows forms application I was getting an immediate “Object reference not set to an instance of an object” exception coming from the Designer file of one of my windows forms. This is probably the most frustrating place in the whole wide world for this to happen since designer classes are auto generated and you are not supposed to edit them. That last bit is a clue, the error isn’t coming from the designer class because you are not supposed to edit it.

If you see a wretched error like this when you open your design view for a windows form:

Then it can be a few things, sometimes it happens for no reason at all and the best way to fix it is to close the window and re-open it. If it still gives you crap restart visual studio. If it still gives you a problem then you have a bigger problem. Lucky me, I had a much bigger problem. I created a custom control and added it to my windows form, but the catch is that the error didn’t happen to me until later in the day – which makes absolutely no sense – this is a good example of something that should break but doesn’t when it really really should.

It turns out that the designer file took the liberty of initializing a public property of my control to null, which in turn caused the “Object reference not set to an instance of an object” exception. I figured this out by commenting out the entire body of my control’s class. It then revealed that the designer class was instantiating my public property to null for me without asking… I really didn’t know it would do that, so be ware, the designer will instantiate your public properties for you.

I fixed this by wrapping the code that was blowing up in an If statement that made sure to check if that particular property was null. That fix this horrid problem.

Leave a Reply

Your email address will not be published. Required fields are marked *