C# 使用FindControl()查找控件
我有一个C# 使用FindControl()查找控件,c#,asp.net,findcontrol,C#,Asp.net,Findcontrol,我有一个Literal控件,我正试图找到它,以便在其中插入文本。我有一个包含多个内容占位符的母版页 <asp:Content ID="Content7" ContentPlaceHolderID="MainLinks" runat="server"> <h3>Project Navigation</h3> <ul class="rightColBoxNav"> <asp:Literal ID="litNavLinks" runat="
Literal
控件,我正试图找到它,以便在其中插入文本。我有一个包含多个内容占位符的母版页
<asp:Content ID="Content7" ContentPlaceHolderID="MainLinks" runat="server">
<h3>Project Navigation</h3>
<ul class="rightColBoxNav">
<asp:Literal ID="litNavLinks" runat="server" />
</ul>
</asp:Content>
无济于事。如何确定位置?在母版页中:
var literal = (Literal)FindControl("MainLinks").FindControl("litNavLinks");
literal.Text = sb.ToString();
从视图中:
litNavLinks.Text = sb.ToString();
我会尝试另一种方法 使用用户控件并公开相关属性以获取或设置文本值如何 属性将访问文本控件。但是,调用该属性的页面不会更明智
请记住,我们生活在一个面向对象的世界。我认为您必须这样做,但我现在没有我的代码来再次检查:
Page.Master.FindControl("MainLinks").FindControl("litNavLinks");
ASP是一个“命名容器”(它实现INamingContainer接口)。仅在当前命名容器中搜索具有指定ID的控件
我偶尔会包含一个实用函数,它接受一个“/”分隔的字符串来任意浏览页面上的命名容器。类似于下面的实现。(注意:我没有尝试编译或测试此代码)
我还没有试过,但是你能用litNavLinks.Text=sb.ToString()吗?看看Darin的答案。明天早上我得试试。我没有试过,我打赌它会成功的。如果是这样的话,我觉得自己很愚蠢。我现在觉得自己很愚蠢,认为这是对的。有时是简单的事情让我们绊倒。
Page.Master.FindControl("MainLinks").FindControl("litNavLinks");
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();
Literal tbx = this.Controls.Find("Literal1", true).FirstOrDefault() as Literal;