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?
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>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With