如何在C#中通过字符串获取HtmlGenericControl

How to get HtmlGenericControl by string in C#

我想添加一个 css class 到后面代码中的 li 标签,给定 li 标签的 id。

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

这是我的 C# 代码:

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

我试过上面的方法,但是returns无效。有没有不需要遍历所有页面控件就可以得到li标签的方法?谢谢

您正在查看的控件 li 不会位于页面的顶层,因为它是 ul 的子控件。 FindControl 在顶层找到。您应该在 liOne 的直接父级上调用 FindControl

你已经有 id with li 并且它已经 runat="server" 属性 设置所以你应该可以直接访问它而不需要 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.

编辑根据评论,li控件比较多

您可以分配具有某些序列的 ID,例如 li1、li2、li3,并通过其父级对其进行评估。

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
}