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.

Adil
  • 146,340
  • 25
  • 209
  • 204
Natsuki_Kato
  • 157
  • 1
  • 13

1 Answers1

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
}
Adil
  • 146,340
  • 25
  • 209
  • 204
  • Since I have several li controls in ul tag, I would like to make it more dynamically instead of accessing it directly, thanks. – Natsuki_Kato Mar 14 '17 at 07:56
  • Thanks for your answer, I have made the ul runat server so that the specific li control can be found in code behind. – Natsuki_Kato Mar 14 '17 at 08:00