技术文档
公司介绍
 
递归方式的 FindControl (进阶版)
2008-08-01 05:07

一般 FindControl 方法,大都是以 ID 寻找控件的第一阶的子控件(若控件有多载 FindControl 方法则例外)。之前有发表过一篇「递归方式的 FindControl」的文章,它是以递归方式逐层往下去执行 FindControl,找到指定 ID 的控件。
此篇文章是提供进阶版的 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(ByVal Parent As System.Web.UI.Control, ByVal Type As System.Type, _
 9        ByVal PropertyName As StringByVal PropertyValue As ObjectAs 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(ByVal Component As ObjectByVal PropertyName As StringAs 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"), IButtonControl)

 

作者:jeff377 来源:博客园
 
 
昆明索仕科技开发有限公司 版权所有 Copyright© 2002-2008 Kunming Source Technology Exploitive Co.,LTD. All Rights Reserved.
电话:0871-5627877 5354445 业务QQ:163871 业务 
滇ICP备05000592号

本站基于:索仕网站信息管理系统建设 版本 1.5.3063