views:

439

answers:

1

Hi Everyone.

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!

+3  A: 

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.

Tomas Lycken
@Tomas: Yeah, I had a feeling someone would say that. I think I will go with a user control - makes sense, cheers for the advice. However this came up one other time when I didn't have that option (for some reason... actually I think it had something to do with setting a page dependant class on a body tag in a master page) so I'd still like to know how to go about this for future reference.
Ev
As far as I can tell the FindControl is meant for the purpose you intend. You just have to start finding from a known control that contains the one your after, and recursively use FindControl to drill down through the DOM. You can write something that will crawl your hole page, but this would be a nightmare parformance wise.
Mark Dickinson
@Mark: Yeah, i've seen something like this done recursively before. okay. I might leave this one for the time being.
Ev