Asp.net—递归方式的FindControl

一般 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值