Search code examples
c#asp.netwebformsascxfindcontrol

How to get HtmlGenericControl by string in C#


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.


Solution

  • 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
    }