首先,您应该知道MasterPages实际上位于Pages内部。实际上,MasterPage的Load事件在ASPX的Load事件之后被调用。
这意味着,页面对象实际上是控件层次结构中最高的控件。
因此,在这样的嵌套环境中查找任何控件的最佳方法是编写一个递归函数,循环遍历每个控件和子控件,直到找到您要查找的控件。在本例中,您的MasterPages实际上是主Page控件的子控件。
您可以通过以下方式从任何控件内部访问主Page对象:
C#:
this.Page;
VB.NET
Me.Page
我发现通常控件的FindControl()方法是无用的,因为环境始终是嵌套的。
因此,我决定使用.NET 3.5新的扩展功能来扩展Control类。
通过使用下面的代码(VB.NET),例如,在您的AppCode文件夹中,所有控件现在都将执行通过调用FindByControlID()进行递归查找:
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