I've inherited from an ASP.NET WebControl to add some additional functionality. I tested my control in a blank ASP.NET Web Site (created through File > New Web Site...) and it worked fine. But I can't get it to work when I add it to a Web Application Project (created throgh File > New Project... > Visual Basic > Web > ASP.NET Web Application. I personally prefer Web Sites for ease of development, but the project leadership I'm working with now wants to keep it a Web Application (they like how it pre-compiles all page code-behind into a single DLL in the Bin folder.)
To isolate the issue I tried to reproduce it using the simple MSDN Walkthrough: Developing and Using a Custom Server Control. To my surprise, I had the same issue there: If you build it into an ASP.NET Web Application Project, and then try to access the instance of the control from the page's code-behind, you get the compilation error BC30456: 'WelcomeLabel1' is not a member of 'WebApplication1._Default'. E.g., in Page Load, write:
Me.WelcomeLabel1.Text = "foo"
However, if you simply remove that line of code behind, it compiles properly and the browser shows the page with the label formatted correctly. To me this is a bug in the compiler/framework, because if the control gets injected properly into the page, it should always be available in the code-behind, right?
Any ideas? I suppose I could compile my control into an assembly as suggested further into the walkthrough, but that seems like overkill.
Interestingly, I can use FindControl to get a reference to the WelcomeLabel, but I am unable to cast it to the appropriate type. Doing so causes the error "Unable to cast object of type 'Samples.AspNet.VB.Controls.WelcomeLabel' to type 'WebApplication2.Samples.AspNet.VB.Controls.WelcomeLabel'." I've tried every combination of namespaces and imports that I could think of, even adding declarations to the designer.vb file manually, and I can't get this to work, unless of course I switch to a Web Site project, which I can't do.
UPDATE 1.1:
To clarify, what I was trying to achieve was:
- Web Application Project
- Inherited web control class file in the same assembly (i.e. not referenced from a separate compiled DLL)
- Control added to page through design-time markup
- Control instance referenced from page code-behind
EDIT: After re-reading Bryan's comments, I finally understood. It's very simple actually: all you have to do is add Assembly="WebApplication1" to the <%@Register%> directive in the markup, and add the "WebApplication1." prefix to the Namespace directive. So:
<%@ Register Assembly="WebApplication1" TagPrefix="aspSample" Namespace="WebApplication1.Samples.AspNet.VB.Controls" %>
And now you should have no problem instantiating the control through markup and accessing the instance from code-behind, whether you place the control's class file in App_Code or anywhere else.
Jordan Rieger