Asp.net—递归方式的FindControl

一般 FindControl 方法,大都是以 ID 寻找控件的第一阶的子控件(若控件有多载 FindControl 方法则例外)。之前有发表过一篇「
递归方式的 FindControl」的文章,它是以递归方式逐层往下去执行 FindControl,找到指定 ID 的控件。
此篇文章是提供进阶版的 FindControl,此方法一样是以递归方式逐层往下去执行 FindControl,不过它不限只能以 ID 去寻找控件,而是指定「型别、属性名称、属性值」去寻找符合的控件。

     /**/''' <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)


原文来自:雨枫技术教程网 http://www.fengfly.com
原文网址:http://www.fengfly.com/plus/view-141454-1.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值