3

我有一个注册了 2 个用户控件的 ASP.NET 页面。第一个只有一个按钮。第二个是简单的文本,默认隐藏。我想要的是在单击第一个按钮时使第二个可见(即在按钮单击事件上)。

ASP.NET 页面:

<%@ Page Title="" Language="C#" CodeFile="test.aspx.cs" Inherits="test" %>
<%@ Register Src="~/UC_button.ascx" TagName="button" TagPrefix="UC" %>
<%@ Register Src="~/UC_text.ascx" TagName="text" TagPrefix="UC" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MyTestContent" Runat="Server">
    <UC:button ID="showbutton1" runat="server" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MyTestContent2" Runat="Server">
    <UC:text runat="server" Visible="false" ID="text1" />
</asp:Content>

UC_Button.ascx.cs:

protected void button1_Click(object sender, EventArgs e)
{
    Button btnSender = (Button)sender;
    Page parentPage = btnSender.Page;
    UserControl UC_text = (UserControl)parentPage.FindControl("text1");
    UC_text.Visible = true;
}

我究竟做错了什么?我在代码的最后一行得到了众所周知的Object reference not set to an instance of an object.错误。

编辑:

我第一次发布这个时忘记提到的一件事。用户控件位于不同的<asp:Content></asp:Content>控件中(我编辑了上面的示例)。如果我把它们放在同一个占位符代码中就可以了。如果我将它们放在单独的内容占位符中,我无法使用 findcontrol 以任何方式找到它们。为什么会这样,我怎样才能找到它们?

4

4 回答 4

6

请检查以下内容:

UserControl UC_text = (UserControl)this.NamingContainer.FindControl("text1");
于 2011-07-26T10:04:24.720 回答
2

FindControl 方法不对控件进行深度搜索。它直接在您为请求的控件指定的位置中查找。

就您而言,您需要做的是:

UserControl UC_text = (UserControl)Content1.FindControl("text1");

您还可以在这里看到我的问题:IEnumerable and Recursion using yield return,它演示了一种按类型查找深层控件的方法。

于 2011-07-26T09:47:36.470 回答
2

好的,我找到了解决方案,直到找到更好的解决方案。问题是,正如 Jamie Dixon 指出的(谢谢 Jamie):

The FindControl method does not do a deep search for controls. It looks directly in the location you specify for the control you're requesting.

因此,因为我在不同的 contentplaceholders 中有用户控件,所以我必须首先找到目标占位符(用户控件所在的位置),然后我可以在其中搜索用户控件:

protected void Dodaj_Feed_Panel_Click(object sender, EventArgs e)
    {
        ContentPlaceHolder MySecondContent = (ContentPlaceHolder)this.Parent.Parent.FindControl("MyTestContent2");

        UserControl UC_text = (UserControl)MySecondContent.FindControl("text1");
        UC_text.Visible = true;
    }

真正让我烦恼和困惑的是这this.Parent.Parent部分,因为我知道这不是最好的解决方案(如果我稍微改变层次结构,这段代码会中断)。这部分代码实际上所做的是它在页面层次结构中向上移动了两个级别(即两个用户控件所在的页面)。我不知道有什么区别,this.Page因为对我来说这意味着相同但对我不起作用。

长期解决方案类似于服务器端“类似 jQuery 的选择器”(无论它们在层次结构中的什么位置,它都可以找到元素)。有人有更好的解决方案吗?

于 2011-07-27T12:23:06.257 回答
0

使用用户控件的id,然后将控件(例如文本框)放在面板中,然后从主页尝试此代码

例子:

TextBox txt = (TextBox)showbutton1.FindControl("Textbox1");

使用 udpatepanel 进行更新:TextBox txt = (TextBox)showbutton1.FindControl("Textbox1"); txt.Text="你好世界!";

((UpdatePanel)showbutton1.FindControl("UpdatePanel1")).Update();
于 2017-03-21T02:33:42.240 回答