Search code examples
c#asp.netinheritancehyperlinkfindcontrol

Finding a Control in a page from a page base class


Hope you're having a good Friday and stuff... okay, so here's my question:

All my ASPX pages inherit from a base class called BasePage. BasePage inherits from:

System.Web.UI.Page

Now, how do I access/set a control in my aspx page from my page base? I've tried this:

HyperLink hypMainMenu = (HyperLink)Page.FindControl("hypMainMenu");
hypMainMenu.NavigateUrl = AppConfiguration.AppSettings.Urls.MainMenu;

But hypMainMenu is always null - I can't find the bastard. Any ideas? Or is this bad practice and someone can reccommend a better way to do this?

Thanks in advance!


Solution

  • Even though what is and is not good practice is very subjective, I must say that trying to access anything from a control from it's base class is bad practice. A base class should only contain code that is relevant for all classes that will inherit it, and how do you know that every page you write in the future will have this control?

    A better way to solve your problem (which I assume to be having code for your main menu in only one place) would be to write a UserControl and which you include on every page. If you need to do something specific with that control, you can do it in the UC's CodeBehind.