Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of FindControl() for use with <li>

I have an <li> on my page. It has runat="server". I can now reference this li directly in code-behind. However, as I do with other controls on the page, I need to find it based on a string value that should match it's ID.

As part of a loop I have:

var li = Page.FindControl("li" + i);

Ultimately wanting to change the class of the li. But I don't seem to have access to any attributes just as I would if I had referenced the li directly. What have I done wrong here? Is there another method for amending an li's attributes from code-behind?


1 Answers

As you are using generic html elements on the server-side, you will get an instance of HtmlGenericControl when accessing the <li> on the server. The HtmlGenericControl class does not support the Class or CssClass properties as do most .NET web controls. Still you can change the class via the Attributes collection:

var li = (HtmlGenericControl) Page.FindControl("li" + i);
li.Attributes["class"] = "myCssClass";

The Page.FindControl("li" + i) method requires a valid control ID. Therefore, you need to also add an id for the <li> elements:

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

If you are creating a dynamic list inside a repeater or list view control, however, this may not work for you, as the id's will get prefixed by the parent control. You should hook to the appropriate item created event for the repeater/list view control in order to programatically access the <li>.

like image 130
Ivaylo Slavov Avatar answered Dec 03 '25 19:12

Ivaylo Slavov