

/**/''' <summary>
''' 递归寻找符合条件的控件。
''' </summary>
''' <param name="Parent">父控件。</param>
''' <param name="Type">欲寻找的控件型别。</param>
''' <param name="PropertyName">比对的属性名称。</param>
''' <param name="PropertyValue">比对的属性值。</param>
Public Overloads Shared Function FindControlEx()Function FindControlEx(ByVal Parent As System.Web.UI.Control, ByVal Type As System.Type, _
ByVal PropertyName As String, ByVal PropertyValue As Object) As Object
Dim oControl As System.Web.UI.Control
Dim oFindControl As Object
Dim oValue As Object
For Each oControl In Parent.Controls
If Type.IsInstanceOfType(oControl) Then
'取得属性值
oValue = GetPropertyValue(oControl, PropertyName)
If oValue.Equals(PropertyValue) Then
Return oControl '型别及属性值皆符合则回传此控件
End If
Else
If oControl.Controls.Count > 0 Then
'递归往下寻找符合条件的控件
oFindControl = FindControlEx(oControl, Type, PropertyName, PropertyValue)
If oFindControl IsNot Nothing Then
Return oFindControl
End If
End If
End If
Next
Return Nothing
End Function

/**/''' <summary>
''' 取得对象的属性值。
''' </summary>
''' <param name="Component">具有要撷取属性的对象。</param>
''' <param name="PropertyName">属性名称。</param>
Public Shared Function GetPropertyValue()Function GetPropertyValue(ByVal Component As Object, ByVal PropertyName As String) As Object
Dim Prop As PropertyDescriptor = TypeDescriptor.GetProperties(Component).Item(PropertyName)
Return Prop.GetValue(Component)
End Function
例如我们要寻找 FormView 控件中一个 CommandName="Insert" 的 LinkButton(ID="FormView1") 控件,则可以如下呼叫 FindControlEx 方法。
Dim oLinkButton As LinkButton
oLinkButton = CType(FindControlEx(FormView1, GetType(LinkButton), "CommandName", "Insert"), LinkButton)
如果你要寻找的按钮有可能为 Button、LinkButton、ImageButton任一型别的按钮,因为这些按钮都有实作 System.Web.UI.WebControls.IButtonControl 接口,所以也可以利用 IButtonControl 接口去寻找更有弹性。
Dim oButtonControl As IButtonControl
oButtonControl = CType(FindControlEx(FormView1, GetType(IButtonControl), "CommandName", "Insert"), IButtonControl)