Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Class to an anchor link

I have this code to add the class:

(Master.FindControl("ControlName")).Attributes.Add("class", "menu-selected");

But this doesn't work for the link:

<a href="Default.aspx" id="mnuHome" runat="server">Home</a>

But throws the error:

'System.Web.UI.Control' does not contain a definition for 'Attributes' and no extension method 'Attributes' accepting a first argument of type 'System.Web.UI.Control' could be found (are you missing a using directive or an assembly reference?)

I could turn all my links into Hyperlink server controls but this gets really messy, I'd rather keep it like this if possible. Is it?

like image 495
Tom Gullen Avatar asked Dec 19 '25 22:12

Tom Gullen


1 Answers

You need to cast your control:

((HtmlAnchor)(Master.FindControl("ControlName"))).Attributes.Add("class", "menu-selected");

UPDATE
It is HtmlAnchor, not the previously state HtmlGenericControl.

like image 148
Dustin Laine Avatar answered Dec 22 '25 13:12

Dustin Laine