icon_dotnet

Friday Quick Tip : Selecting Active Nav with C# .NET

This little quick tip is nothing new or groundbreaking, but I know that when I first started out with .NET it stumped me for a bit. Let’s learn how to select that active navigation item with C# in a master page

This little quick tip is nothing new or groundbreaking, but I know that when I first started out with .NET it stumped me for a bit. Let’s learn how to select that active navigation item with C# in a master page

Here’s the code in my Master Page, nothing too complex, just a simple UL with links. Notice that each link has a unique ID:

Here’s the code from my code behind on my Default.aspx.cs (This page loads the master file mentioned above)

    protected void Page_Load(object sender, EventArgs e)
    {
        var selectedNav = (HyperLink)Master.FindControl("home");
        selectedNav.CssClass = "selected";
    }

The above code will look through the master page and find the control with the id of “home” and apply the css class of “selected”. You can then target this selected item with CSS to indicate an active page state.

You can use the Master.FindControl to get access to pretty much anything that is in your master page, you’re not limited to Hyperlinks.