使用 FindControl() 查找控件
我有一个 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>
我不断收到“对象引用未设置到对象实例”的信息。如何找到该对象以便找到并更新它?
我已经尝试过了:
((Literal)Page.FindControl("litNavLinks")).Text = sb.ToString();
((Literal)Page.Page.FindControl("litNavLinks")).Text = sb.ToString();
((Literal)Page.FindControl("Content7").FindControl("litNavLinks")).Text = sb.ToString();
没有效果。我如何确定位置?
I have a Literal
control that I am trying to locate so I can insert text into it. I have a Master page that contains several content placeholders.
<asp:Content ID="Content7" ContentPlaceHolderID="MainLinks" runat="server">
<h3>Project Navigation</h3>
<ul class="rightColBoxNav">
<asp:Literal ID="litNavLinks" runat="server" />
</ul>
</asp:Content>
I keep getting "Object reference not set to an instance of an object." How do I locate this object so I can find and update it?
I have tried:
((Literal)Page.FindControl("litNavLinks")).Text = sb.ToString();
((Literal)Page.Page.FindControl("litNavLinks")).Text = sb.ToString();
((Literal)Page.FindControl("Content7").FindControl("litNavLinks")).Text = sb.ToString();
to no avail. How do I determine the location?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从母版页内:
从视图内:
From within the masterpage:
From within the view:
我会尝试不同的方法。
如何使用用户控件并公开相关属性来获取或设置文本值。
该属性将访问文字控件。然而,调用该属性的页面也不会更明智。
请记住,我们生活在面向对象的世界中。
I would try a different approach.
How about using a user control and exposing the relevant properties to get or set the text value.
The property would be accessing the literal control. However, the page calling the property wouldn't be any wiser.
Remember we live in a OO world.
我认为你必须这样做,但我现在没有代码可以仔细检查:
I think you have to do this, but I don't have my code to double-check right now:
ASP ContentPlaceHolder 控件 是一个“命名容器”(它实现 INamingContainer 接口)。仅 Control.FindControls 方法在当前命名容器中搜索具有您指定的 ID 的控件。
我偶尔会包含一个实用程序函数,它接受“/”分隔的字符串,以便在页面上的命名容器中任意导航。类似下面的实现。 (注意:我没有尝试编译或测试此代码)
因此,在您的情况下,您应该能够执行以下操作:
或
The ASP ContentPlaceHolder control is a "naming container" (it implements the INamingContainer interface). The Control.FindControls method only searches within the current naming container for a control with the ID that you specify.
I've occassionally included a utility function that accepts a "/" delimited string to arbitrarily navigate through the naming containers on a page. Something like the following implementation. (Note: I have not tried to compile or test this code)
So, in your case you should be able to do the following:
or