2016-11-13 61 views
0

我在擁有主頁的頁面(test1.aspx)上有一個標籤控件。我想使用FindControl從test1.aspx頁面(不是主頁面)後面的代碼訪問標籤控件。在ContentBody中查找標籤控件

我可以使它直接使用Button2(見下文),但我希望能夠使用FindControl來完成它(請參閱下面的Button1)。我得到一個NULLReference異常,我相信因爲我不知道適當的語法來定位內容控件中的標籤控件。

在沒有母版頁的頁面上我只是使用FindControl(「MenuItemName1」),但因爲控件位於Content3/ContentBody中,所以我相信我需要更多。任何幫助將不勝感激。

<%@ Page Title="" Language="VB" MasterPageFile="~/Shared/MasterPages/SiteLayout.Master" AutoEventWireup="false" CodeFile="Test1.aspx.vb" Inherits="Test1" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="StyleSheetPage" Runat="Server"> 
</asp:Content> 
<asp:Content ID="Content3" ContentPlaceHolderID="ContentBody" Runat="Server"> 

     <asp:Label ID="lblMenuItemName1" runat="server" Text="Label"></asp:Label><br /><br /> 
<asp:Button ID="Button1" runat="server" Text="Button" /><br /><br /> 
<asp:Button ID="Button2" runat="server" Text="Button" /> 
    </asp:Content> 

<asp:Content ID="Content4" ContentPlaceHolderID="JavaScriptPage" Runat="Server"> 
    </asp:Content> 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim C As Content 
    C = CType(Me.FindControl("Content3"), Content) 
    Dim lblMenuItemName As Label = C.FindControl("lblMenuItemName1") 
    lblMenuItemName.Text = "hello" 
End Sub 

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
    lblMenuItemName1.Text = "Direct" 
End Sub 

回答

0

找到了解決方案:

Dim lblMenuItemName As Label = TryCast(Master.FindControl("ContentBody").FindControl("lblMenuItemName1"), Label)