通过名字来控制,包括孩子
本文关键字:包括 孩子 控制 | 更新日期: 2023-09-27 18:19:24
我试图通过名称获得控件。我写了下面的代码:
public Control GetControlByName(string name)
{
Control currentControl;
for(int i = 0,count = Controls.Count; i < count; i++)
{
currentControl = Controls[i];
if (currentControl.HasChildren)
{
while (currentControl.HasChildren)
{
for(int x = 0,size = currentControl.Controls.Count; x < size; x++)
{
currentControl = currentControl.Controls[x];
if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return currentControl;
}
}
}
}
else
{
if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return currentControl;
}
}
}
return null;
}
它只返回null。有人能指出我的错误吗?欢迎任何帮助或改进此代码的方法。
使用控件集合查找方法:
var aoControls = this.Controls.Find("MyControlName", true);
if ((aoControls != null) && (aoControls.Length != 0))
{
Control foundControl = aoControls[0];
}
我实际上在工作中写了一些扩展方法来做这件事:
public static class MyExensions ()
{
public static Control FindControlRecursively (this Control control, string name)
{
Control result = null;
if (control.ID.Equals (name))
{
result = control;
}
else
{
foreach (var child in control.Children)
{
result = child.FindControlRecursively (name);
if (result != null)
{
break;
}
}
}
return result;
}
public static T FindControlRecursively<T> (this Control control, string name)
where T: Control
{
return control.FindControlRecursively (name) as T;
}
}
注意:为了简单起见,删除了Null检查。
您可以使用它来查找,例如,表单上的TextBox
,如下所示:
public class MyForm : Form
{
public void SetSomeText ()
{
var control = this.FindControlRecursively<TextBox> ("myTextboxName");
if (control != null)
{
control.Text = "I found it!";
}
// Or...
var control2 = this.FindControlRecursively ("myTextboxName2") as TextBox;
if (control != null)
{
control2.Text = "I found this one, also!";
}
}
}
编辑
当然,这是一个深度优先算法,它可能很慢,这取决于你的控制链的深度。如果您发现它太慢,您可以将其重写为使用宽度优先算法。如果您的不使用System.Windows.Forms
(这是.Find(string, bool)
工作的东西)
public static class MyExensions
{
public static Control FindControlRecursively(this Control control, string name)
{
Control result = null;
if (control.ID.Equals(name))
{
result = control;
}
else
{
for (var i = 0; i < control.Controls.Count; i++)
{
result = control.Controls[i].FindControlRecursively(name);
if (result != null)
{
break;
}
}
}
return result;
}
public static T FindControlRecursively<T>(this Control control, string name)
where T : Control
{
return control.FindControlRecursively(name) as T;
}
}
注。是的,我知道这是一个老问题,但如果它有帮助