Introduction
When I went into the office the other morning, there was a note on my desk from one of my colleagues asking me for a favour. Whilst working late, he came across a problem when running an ASP.Net page where it fell over with a null reference exception. There is nothing new there, of course, but this error was occurring on a page that many other people had been running and testing without a problem. He asked me to try it out on my machine and see if it was something on his machine only. Spoiler alert! It was the Evil Designer Files.
Everything Worked
I ‘Got Latest’ from TFS, built the page and ran the tests asked of me – no error – everything ran perfectly.
I went through various potential causes when my colleague came in. I have had this problem several times, and it can be one of several problems: –
- The code is not compiled, and you are running a different application version.
- The IIS settings are pointing at a different application folder, and you are, therefore running a different version of the application.
- You haven’t built the application using the correct configuration settings, and you are, therefore, running a different version of the application.
- The evil designer files are out to get you.
As you might imagine, I checked items 1 to 3 and confirmed he was running the correct version of the application. The only thing left to check was the designer file.
We ran the application and could see the null-reference error. We debugged the application and stopped it on the line that was about to access a panel control in the markup and in the compiled application, and it was null.
At that point, my colleague said a rude word about Microsoft!
How to fix it
I then went on to show him a simple way of rectifying the problem.
- Delete the page.aspx.designer.cs file by right-clicking it in Solution Explorer and selecting Delete.
- Right-click on the page.aspx file and click Convert to Web Application.
We then recompiled the application, reran the page and all was well.
This is something that happens from time to time in Visual Studio. The designer files and Visual Studio seem to get into some mess while you are developing the code. It typically happens when you edit the markup, copy/paste controls, and perhaps rename a control or two.
However, this was the first time it happened when someone did a Get Latest from TFS and rebuilt the application.
I thought I would write it down here to help others.
The official documentation for webforms is here: – https://learn.microsoft.com/en-us/aspnet/web-forms/