C# - How to change HTML elements attributes

In order to access these controls from the server-side, you need to make them runat="server"

<ul id="nav" runat="server">
  <li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>               
  <li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li>
  <li id="future"><a href="future.aspx" title="Future">Future</a></li>
  <li id="news"><a href="news.aspx" title="News">News</a></li>
  <li id="download"><a href="download.aspx" title="Download">Download</a></li>
  <li id="home"><a href="index.aspx" title="Home">Home</a></li>
  <li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>

in the code-behind:

foreach(Control ctrl in nav.controls)
{
   if(!ctrl is HtmlAnchor)
   {
      string url = ((HtmlAnchor)ctrl).Href;
      if(url == GetCurrentPage())  // <-- you'd need to write that
         ctrl.Parent.Attributes.Add("class", "active");
   }
}

The code below can be used to find a named control anywhere within the control hierarchy:

public static Control FindControlRecursive(Control rootControl, string id)
{
    if (rootControl != null)
    {
        if (rootControl.ID == id)
        {
            return rootControl;
        }

        for (int i = 0; i < rootControl.Controls.Count; i++)
        {
            Control child;

            if ((child = FindControlRecursive(rootControl.Controls[i], id)) != null)
            {
                return child;
            }
        }
    }

    return null;
}

So you could do something like:

Control foundControl= FindControlRecursive(Page.Master, "theIdOfTheControlYouWantToFind");
((HtmlControl)foundControl).Attributes.Add("class", "active");

Forgot to mention previously, that you do need runat="server" on any control you want to be able to find in this way =)


Add runat="server" on the li tags in the masterpage then add this to the appropriate page_load event to add the 'active' class to the li in the masterpage

HtmlGenericControl li = HtmlGenericControl)Page.Master.FindControl("screenshots"); li.Attributes.Add("class", "active");

Tags:

C#

Html

Asp.Net