2011-07-26 26 views
3

我有一個ASP.NET頁面,註冊了2個用戶控件。第一個只有一個按鈕。第二個是簡單的文本,並在默認情況下隱藏。我想要的是當點擊第一個按鈕(即按鈕單擊事件)時,使第二個按鈕可見。如何在該ASP.NET頁面上的另一個用戶控件的事件中查找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的方式找到它們。爲什麼是這樣,我怎麼找到他們?

回答

2

好,我找到解決方案直到更好的來我的方式。問題是,傑米迪克森指出(謝謝你,傑米):

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的選擇器」(它可以找到元素,無論他們在層次結構中)。任何人有更好的解決方案?

+2

更好的解決方案:MVC :) – drzaus

2

FindControl方法不會深入搜索控件。它直接位於您爲要請求的控件指定的位置。

在你的情況,你需要做的是一樣的東西:

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

您還可以看看我的問題在這裏:IEnumerable and Recursion using yield return演示按類型尋找深控制的方法。

+0

頁面的內容1不可見/可從該頁面的內部用戶控件訪問(或者我完全錯了嗎?) – Janez

+0

我認爲你是對的。看看你的代碼,你應該簡單地直接引用text1,而不必使用FindControl。 –

+0

我在不同的內容佔位符中有用戶控件,所以我不能直接引用它(給出相同的錯誤)。見上面我更新了我的問題。 – Janez

6

請檢查以下內容:

UserControl UC_text = (UserControl)this.NamingContainer.FindControl("text1"); 
0

使用用戶控件的id,然後把控件(例如,克文本框)的內部面板然後 從主網頁嘗試這個代碼

例如:

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

用於與udpatepanel更新: 文本框的txt =(文本框)showbutton1.FindControl( 「Textbox1的」); txt.Text =「Hello World!」;

((UpdatePanel)showbutton1.FindControl("UpdatePanel1")).Update(); 
相關問題