1

I want to add a css class to a li tag in code behind given the id of the li tag.

<li id="liOne" runat="server" class=""></li>

Here is my c# code:

System.Web.UI.HtmlControls.HtmlGenericControl ctrl = Page.FindControl("liOne") as System.Web.UI.HtmlControls.HtmlGenericControl;
if(ctrl!=null)
  ctrl.Attributes["class"] += " active";

I have tried the above method but it returns null. Is there any method that does not require iterating over all page controls to get the li tag? Thanks.

1 Answer 1

1

The control li you are looking wil not be on top level of page as it would be child of ul. The FindControl finds on top level. You should call FindControl on immediate parent of liOne.

You already have id with li and it is already runat="server" property set so you should by able to access it directly withouth FindControl.

liOne.Attributes["class"] += " active";

Page.FindControl

The FindControl method can be used to access a control whose ID is not available at design time. The method searches only the page's immediate, or top-level, container; it does not recursively search for controls in naming containers contained on the page. To access controls in a subordinate naming container, call the FindControl method of that container.

Edit Based on comments, there are many li controls

You can assign ids having some sequence like li1, li2, li3 and assess them through their parent.

for(int i=1; i < 4; i++)
{
   System.Web.UI.HtmlControls.HtmlGenericControl ctrl = ul1.FindControl("li" + i) as System.Web.UI.HtmlControls.HtmlGenericControl;
   //Do what you want with ctrl
}
Sign up to request clarification or add additional context in comments.

2 Comments

Since I have several li controls in ul tag, I would like to make it more dynamically instead of accessing it directly, thanks.
Thanks for your answer, I have made the ul runat server so that the specific li control can be found in code behind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.