Using Visual Studio 2010, I added a form to an ASP.Net page that was already part of my project. Call it myPage.aspx. I was actually copying and pasting the form from a working page in another application. So first I pasted the .aspx code into myPage.aspx file and then the C# code into the myPage.aspx.cs file. I did not copy over the page directive in the myPage.aspx file, and I did not copy over any of the class declaration code in the myPage.aspx.cs file. I only pasted a table into the body of myPage.aspx and some submit handling code into myPage.aspx.cs.
When I tried to build the web site, I got errors for every single control saying “The name ‘whateverControl’ does not exist in the current context”. This made no sense to me because the Intellisense was working, finding the controls just fine. I double checked the CodeFile and Inherits attributes of the Page and they were all correct.
Furthermore, if I used the “Build Page” command, the page built successfully. It was only if I used “Build Web Site” that I got the long list of “does not exist” errors. “Rebuild Web Site” did not help. I even shutdown Visual Studio and reopened it and it made no difference. I eventually found the problem, so I am answering my own question here.
It turned out that myPage.aspx and myPage.aspx.cs were completely fine. The problem was that at some previous time, someone else had copied the .aspx page (not the .aspx.cs) I was working on to two other .aspx pages and they had also copied the CodeFile and Inherits attributes when they did this. So both of those pages had the exact same CodeFile and Inherits settings as the page I was working on. That meant three pages had these exact same settings in their Page directive:
CodeFile=”myPage.aspx.cs” Inherits=”myPage”
Apparently this is allowed by the compiler, and it works as long as there is no code in the .aspx.cs file that is looking for controls that only exist in one of the pages.
I removed those attributes from the two other copied pages and then everything compiled successfully.