Introduction
In this tip, I am going to explore how to highlight the current page in ASP.NET master page. In earlier days, highlighting the current page in HTML, we used to add style class attribute in each page. In ASP.NET master page, it’s very easy to highlight the current page and it makes the developer's life easier. Follow the simple steps to highlight the current page in ASP.NET master page.
Step 1
In the master page, add two image buttons:
<form id="form1" runat="server">
<div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td><asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/home.gif"
BorderStyle="None" BorderWidth="0px" EnableViewState="False"
onclick="ImageButton1_Click" /></td>
<td><asp:ImageButton ID="ImageButton2"
runat="server" ImageUrl="~/images/about.gif" BorderStyle="None"
BorderWidth="0px" EnableViewState="False" onclick="ImageButton2_Click" /></td>
</tr></table>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
Step 2
In each content page, add the following code to access the master page controls:
<%@ MasterType VirtualPath=”~/MasterPage.master” %>
Step 3
Let’s add the following code in each content page Page Load to change the images dynamically.
Default.aspx
protected void Page_Load(object sender, EventArgs e)
{
ImageButton img = (ImageButton)this.Master.FindControl("ImageButton1");
img.ImageUrl = "~/images/home-over.gif";
}
Default2.aspx
protected void Page_Load(object sender, EventArgs e)
{
ImageButton img = (ImageButton)this.Master.FindControl("ImageButton2");
img.ImageUrl = "~/images/about-over.gif";
}
Look into the below images before applying and after applying the codes.
Before
After
Default.aspx
Default2.aspx