I wrote about this already, but I just wanted to write a post about a very very weird encounter with this error while working with Win Forms. I kept getting the dreaded “Object reference not set to an instance of an object” error, but it wouldn’t break the designer and stop me from compiling, it would happen after compiling and pop-up a message box with the error in it.
This had me scratching my head for a good two weeks until today.
Turns out that the reason the message was popping up in a message box is because of code I wrote that was wrapped in a try/catch block and in the catch I was returning the exception message in a message box. Now the question is, why?
Well oddly enough, I am using a web service to populate a bunch of items in a combo box and during recompile since the service isn’t available during design mode it blows up when it tries to access the source. So it looks something like this:
Try comboBox.DataSource = WebServiceClient.GetRemoteObjects() comboBox.DisplayMember = "ObjectName" comboBox.ValueMember = "ObjectID" Catch ex As Exception MessageBox.Show(ex.Message) 'Throws the message during recompile only while form designer is open - how weirdly convenient? End Try
The problem was that when looking at this code, the design mode blows up because the WebServiceClient (singleton object) is null (or Nothing) during the build process in design view. It is only instantiated in run time.
'Make sure to check that the proxy object (client) is not null before using it - this apparently matters more during design view If WebServiceClient IsNot Nothing Then Try comboBox.DataSource = WebServiceClient.GetRemoteObjects() comboBox.DisplayMember = "ObjectName" comboBox.ValueMember = "ObjectID" Catch ex As Exception MessageBox.Show(ex.Message) End Try End If
This is truly a stupid issue and a giant waste of time, but hey I am glad to have figured it out with some help from a friend.