Shocking Gotcha – ASP.NET user controls not being referenced
July 4, 2008 · 2 minute read
Sometimes I just want to quit and take up kite flying or something…
I was extending a feature for a site that used a user control called that had a class name of controls_searchboxui embedded in an aspx page.
The new functionality meant that further user controls were to be created and only one of them would be programitcally added to the page based on the value of a querystring.
So I added a user control called advancedsearchui to a folder on my site called “controls” and it assumed the object name controls_advancedsearchui.
I then removed the embedded user control from my search.aspx page and added a place holder called searchPlaceHolder in its place.
The page would look at the value of the querystring “searchtype” on the url and run the following code to add the required control to the placeholder:
- string UsageMode = (string) Request.QueryString["searchtype"];
- switch (UsageMode)
- {
- case "adv":
- controls_advancedsearchui AdvancedSearchBox = (controls_advancedsearchui) LoadControl("~/controls/advancedsearchui.ascx");
- searchPlaceHolder.Controls.Add(AdvancedSearchBox);
- AdvancedSearchBox.Search +=new AdvancedSearchRaised(doAdvancedSearch);
- break;
- default:
- controls_searchboxui SimpleSearchBox = (controls_searchboxui) LoadControl("~/controls/searchboxui.ascx");
- searchPlaceHolder.Controls.Add(SimpleSearchBox);
- SimpleSearchBox.Search += new SimpleSearchRaised(doSimpleSearch);
- break;
- }
When i tried to build the solution, it failed and I got the following message :
The type or namespace name ‘controls_clientsearchui’ could not be found (are you missing a using directive or an assembly reference?)
say it with me…. WTF?
I invoked intelli(non)sense and sure enough, while controls_searchboxui was present, my new user control wasn’t.
The only difference between the two was that the controls_searchboxui object had been embedded on a page before now….
I dragged the control onto the page and immediately deleted it.
Hey Presto : the user control could now be referenced.
If anyone can explain this bizarre behaviour, please let me know… otherwise, I hope this helps and saves you some time.