はまず、あなたはMasterPagesが実際にページ内に座っていることを知っている必要があります。あなたのASPXのLoadイベントの後にMasterPageのLoadイベントが実際に呼び出されるように。
これは、実際にはPageオブジェクトがコントロール階層内の最も高いコントロールであることを意味します。
このように、ネストされた環境でコントロールを見つける最良の方法は、探しているものが見つかるまで、すべてのコントロールと子コントロールをループする再帰関数を作成することです。この場合、マスターページは実際にはメインページコントロールの子コントロールです。
あなたはこのような任意のコントロールの内側からメインページオブジェクトを取得:
のC#:
this.Page。
VB.NET
Me.Page
私は的環境は常にネストされているとして、通常は、コントロールのクラスにFindControl()メソッドは、かなり無用であることがわかります。
この場合、.NETの3.5の新しい拡張機能を使用してControlクラスを拡張することにしました。あなたのAppCodeフォルダ、と言うには、コードの下(VB.NET)を使用することにより
、すべてのコントロールは今FindByControlIDを呼び出すことにより、再帰的な検索をpeformます()
Public Module ControlExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Function FindControlByID(ByRef SourceControl As Control, ByRef ControlID As String) As Control
If Not String.IsNullOrEmpty(ControlID) Then
Return FindControlHelper(Of Control)(SourceControl.Controls, ControlID)
Else
Return Nothing
End If
End Function
Private Function FindControlHelper(Of GenericControlType)(ByVal ConCol As ControlCollection, ByRef ControlID As String) As Control
Dim RetControl As Control
For Each Con As Control In ConCol
If ControlID IsNot Nothing Then
If Con.ID = ControlID Then
Return Con
End If
Else
If TypeOf Con Is GenericControlType Then
Return Con
End If
End If
If Con.HasControls Then
If ControlID IsNot Nothing Then
RetControl = FindControlByID(Con, ControlID)
Else
RetControl = FindControlByType(Of GenericControlType)(Con)
End If
If RetControl IsNot Nothing Then
Return RetControl
End If
End If
Next
Return Nothing
End Function
End Module
これは完全に機能します。ありがとう。 –
+1これもまた助けてくれました – leen3o
+1これは5歳のようなものですが、この方法は私に頭痛を救った、ありがとう! – psoshmo