Asp.net—递归方式的FindControl

翻译|其它|编辑:郝浩|2008-05-22 10:30:44.000|阅读 1227 次

概述:

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

       一般 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()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
标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:博客

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP