一般 FindControl 函数只能找到第一层子控件,像 GridView、FormView 之类的复合式控件,要寻找包含的子控件就非常麻烦,要明确找到父控件(容器),才能使用 FindControl 去找到子控件。而且一旦所有往上的父控件有任一层的变更时,就需要再去修改程序代码,这样就非常麻烦。
为了解決上述的问题,可以使用递归的方式來进行 FindControl 的操作,这样可以简化FindControl的查找。请参阅以下的 FindControlEx 函数。
vb.net代码:
'''
''' 递归查找找指定ID的控件。
'''
''' 父控件
''' 要查找的控件ID
''' 回传符合ID的控件,若未找到则返回Nothing
Public Function FindControlEx(ByVal Parent As System.Web.UI.Control, ByVal ID As String) As System.Web.UI.Control
Dim oCtrl As System.Web.UI.Control = Nothing
Dim oChildCtrl As System.Web.UI.Control = Nothing
'先使用 FindControl 去查找指定的子控件
oCtrl = Parent.FindControl(ID)
'如果未找到则往下层递归方式去查找
If oCtrl Is Nothing Then
For Each oChildCtrl In Parent.Controls
'以递归方式回调原函数
oCtrl = FindControlEx(oChildCtrl, ID)
'如果找到指定控件则退出循环
If oCtrl IsNot Nothing Then Exit For
Next
End If
Return oCtrl
End Function
c#.net代码:
///
/// 递归查找找指定ID的控件
///
/// 父控件(控件容器)
/// 要查找的控件ID
/// 回传符合ID的控件,若未找到则返回Null
public System.Web.UI.Control FindControlEx(System.Web.UI.Control Parent, string id)
{
System.Web.UI.Control oCtrl = null;
//先使用 FindControl 去查找指定的子控件
oCtrl = Parent.FindControl(id);
//如果未找到则往下层递归方式去查找
if (oCtrl == null)
{
foreach (System.Web.UI.Control oChildCtrl in Parent.Controls)
{
//以递归方式回调原函数
oCtrl = FindControlEx(oChildCtrl, id);
//如果找到指定控件则退出循环
if (oCtrl != null) break;
}
}
return oCtrl;
}
本文作者:pincelee 来源:http://www.cnblogs.com/pincelee/archive/2007/11/06
CIO之家 www.ciozj.com 微信公众号:imciow