运用递归函数找到一个服务器控件,我们时常搞不清楚我们的控件到底在控件树的什么地方!看到老外写了一篇文章,呵呵!不过用递归算法,效率差了些,一般清楚控件树结构的情况下,还是直接用FindControl函数好一点!

This recursive function finds a control on a form by its name.

//written in C#

/// &ltsummary>
///Recursive function to find control on the form by its name
/// </summary>
private Control _co;
private Control _find_control(Control _c, string _name)
{
if (_co != null) return _co;
IEnumerator _ir = _c.Controls.GetEnumerator();
_ir.Reset();
while (_ir.MoveNext())
{
if (_co != null) break;
if (((Control)_ir.Current).Name == _name)
{
_co = ((Control)_ir.Current);
break;
}
_find_control(((Control)_ir.Current),_name);
}
return _co;
}

//usage examples

Form1 _fm = (Form1)this.FindForm();
_co = null;
DataGrid _dg = (DataGrid)_find_control((Control)_fm,"GRID1");
_co = null;
Label _lbl = (Label)_find_control((Control)_fm,"Label1");

By Yuriy Bas in www.devx.com
    posted @ 2006-12-28 21:16 太阳 阅读(43) 评论(0) 编辑