I recently received a question from another programmer I know who’s been using PHP prior to ASP.NET that made me think harder about a problem we’ve all had in ASP.NET. The basic problem is this:
How do you dynamically change the class of a hyperlink based on the page name so that the hyperlink that represents the current page is styled differently than all the other hyperlinks on our screen? If you want you can substitute any other HTML element you want, but the problem remains the same.
The first, most obvious answer would be to create a case statement of some sort.
1 | string fileName = AppRelativeVirtualPath |
But we all know just how ugly that code will get once we start adding pages to our site. Yuck! Unfortunately, this is exactly the code I’ve been recommending up until today.
What was I thinking?!
If you are familiar with ASP.NET at all, you should already be familiar with the Page_Load event handler. I bet that’s where you do 90% of your page initialization. But did you know that there is a load event that fires for each control?
Further, you can have all of your controls point to the same load event handler. So if we take advantage of this, we can write very tight code that automatically sets the class based on the current page name.
1 | // This code assumes that the ID of the hyperLink |