Change a link programmatically in a masterpage with css and c#
asp.net, c#, css, master-pages
Solution
You have few options:
- Add a `runat="server` to your anchor tag
- Use `HyperLink` control instead
ASP:
<asp:HyperLink ID ="ReportHyperLink"
NavigateUrl ="report.aspx"
CssClass="list-group-item" runat="server" />
code behind:
ReportHyperLink.CssClass= "list-group-item active";
cant seem to get the code behind to work if using in a masterpage 'child' page
You just need to find the control
ASP:
<asp:ContentPlaceHolder ID="cpHolder" runat="server">
<asp:HyperLink ID ="ReportHyperLink"
NavigateUrl ="report.aspx"
CssClass="list-group-item" runat="server" />
</asp:ContentPlaceHolder>
code behind:
ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.FindControl("CpHolder");
HyperLink hp= (HyperLink)cp.FindControl("ReportHyperLink");
hp.CssClass= "list-group-item active";
Also a better approach , you can add a public property in the master page like this:
master's code behind:
public string ReportHyperLinkCssClass
{
get {
return this.ReportHyperLink.CssClass;
}
set {
this.ReportHyperLink.CssClass= value;
}
}
Page Load Code
var myMaster = this.Master as YourMasterType;
if(myMaster != null)
{
myMaster.ReportHyperLinkCssClass = newCssClass;
}
Problem
Does anybody know how to programatically change the ccs of a link in a masterpage in child pages? For example I have a (navigation) list of links in my masterpage like so: ``` <div class="list-group"> <a href="report.aspx" class="list-group-item active">Donuts™</a> <a href="english_responses.aspx" class="list-group-item">English responses</a> <a href="irish_responses.aspx" class="list-group-item">Irish responses</a> </div> ``` In the navigation list I use the css class: list-group-item active to display the active link (which is coloured blue for active) and css class:list-group-item for normal links. What I want is to change the active link for each child page programatically using c#. Is there any way to do it with page_load?