在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
此篇文章是提供进阶版的 FindControl,此方法一样是以递归方式逐层往下去执行 FindControl,不过它不限只能以 ID 去寻找控件,而是指定「型别、属性名称、属性值」去寻找符合的控件。 1 /**/''' <summary> 2 ''' 递归寻找符合条件的控件。 3 ''' </summary> 4 ''' <param name="Parent">父控件。</param> 5 ''' <param name="Type">欲寻找的控件型别。</param> 6 ''' <param name="PropertyName">比对的属性名称。</param> 7 ''' <param name="PropertyValue">比对的属性值。</param> 8 Public Overloads Shared Function FindControlEx()Function FindControlEx(ByVal Parent As System.Web.UI.Control, ByVal Type As System.Type, _ 9 ByVal PropertyName As String, ByVal PropertyValue As Object) As Object 10 Dim oControl As System.Web.UI.Control 11 Dim oFindControl As Object 12 Dim oValue As Object 13 14 For Each oControl In Parent.Controls 15 If Type.IsInstanceOfType(oControl) Then 16 '取得属性值 17 oValue = GetPropertyValue(oControl, PropertyName) 18 If oValue.Equals(PropertyValue) Then 19 Return oControl '型别及属性值皆符合则回传此控件 20 End If 21 Else 22 If oControl.Controls.Count > 0 Then 23 '递归往下寻找符合条件的控件 24 oFindControl = FindControlEx(oControl, Type, PropertyName, PropertyValue) 25 If oFindControl IsNot Nothing Then 26 Return oFindControl 27 End If 28 End If 29 End If 30 Next 31 Return Nothing 32 End Function 33 34 /**/''' <summary> 35 ''' 取得对象的属性值。 36 ''' </summary> 37 ''' <param name="Component">具有要撷取属性的对象。</param> 38 ''' <param name="PropertyName">属性名称。</param> 39 Public Shared Function GetPropertyValue()Function GetPropertyValue(ByVal Component As Object, ByVal PropertyName As String) As Object 40 Dim Prop As PropertyDescriptor = TypeDescriptor.GetProperties(Component).Item(PropertyName) 41 Return Prop.GetValue(Component) 42 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 |
请发表评论