ASP ContentPlaceHolder 控件是一个“命名容器”(它实现了INamingContainer 接口)。Control.FindControls 方法仅在当前命名容器中搜索具有您指定的 ID 的控件。
我偶尔会包含一个实用程序函数,它接受“/”分隔的字符串来任意导航页面上的命名容器。类似于以下实现。(注意:我没有尝试编译或测试此代码)
public static Control FindControlByPath(this Control start, string controlPath)
{
if(controlPath == null)
throw new ArgumentNullException("controlPath");
string[] controlIds = controlPath.split('/');
Control current = start;
if(controlIds[0] == "") // in case the control path starts with "/"
current = start.Page; // in that case, start at the top
for(int i=0; i<controlIds.Length; i++)
{
switch(controlIds[i])
{
case "":
// TODO: handle syntax such as "<controlId>//<controlId>", if desired
break;
case ".":
// do nothing, stay on the current control
break;
case "..":
// navigate up to the next naming container
current = current.Parent;
if(current == null)
throw new ArgumentOutOfRangeException("No parent naming container exists.", "controlPath");
while(!(current is INamingContainer))
{
current = current.Parent;
if(current == null)
throw new ArgumentOutOfRangeException("No parent naming container exists.", "controlPath");
}
break;
default:
current = current.FindControl(controlIds[i]);
break;
}
}
return current;
}
因此,在您的情况下,您应该能够执行以下操作:
<some control>.FindControlByPath("/MainLinks/litNavLinks").Text = sb.ToString();
或者
Page.FindControlByPath("MainLinks/litNavLinks").Text = sb.ToString();