How to change CSS class of a HTML page element using ASP.NET?

59,182

Solution 1

The FindControl method searches for server controls. That is, it looks for controls with the attribute "runat" set to "server", as in:

<li runat="server ... ></li>

Because your <li> tags are not server controls, FindControl cannot find them. You can add the "runat" attribute to these controls or use ClientScript.RegisterStartupScript to include some client side script to manipulate the class, e.g.

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("document.getElementById(\"li1\").className=\"newClass\";")
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "MyScript", sb.ToString());

Solution 2

Add runat="server" in your HTML page

then use the attribute property in your asp.Net page like this

li1.Attributes["Class"] = "class1";
li2.Attributes["Class"] = "class2";

Solution 3

FindControl will work if you include runat="server" in the <li>

<li id="li1" runat="server">stuff</li>

Otherwise you server side code can't 'see' it.

Solution 4

This will find the li element and set a CSS class on it.

using System.Web.UI.HtmlControls;

HtmlGenericControl liItem = (HtmlGenericControl) ctl.FindControl("liItemID");
liItem.Attributes.Add("class", "someCssClass");

Remember to add your runat="server" attribute as mentioned by others.

Solution 5

you must set runat="server" like:

<li id="li1" runat="server">stuff</li>
Share:
59,182
Alexander Prokofyev
Author by

Alexander Prokofyev

Data Scientist, married, have a daughter and two sons.

Updated on July 16, 2022

Comments

  • Alexander Prokofyev
    Alexander Prokofyev almost 2 years

    I have several <li> elements with different id's on ASP.NET page:

    <li id="li1" class="class1">
    <li id="li2" class="class1">
    <li id="li3" class="class1">
    

    and can change their class using JavaScript like this:

    li1.className="class2"
    

    But is there a way to change <li> element class using ASP.NET? It could be something like:

    WebControl control = (WebControl)FindControl("li1");
    control.CssClass="class2";
    

    But FindControl() doesn't work as I expected. Any suggestions?

    Thanks in advance!