Jac*_*ack 4 .net c# controls winforms
我想通过名字来控制.我写了以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
它只返回null.有人可以指出我的错误吗?欢迎任何帮助或改进此代码的方法.
com*_*ech 12
只需使用Controls集合查找方法:
var aoControls = this.Controls.Find("MyControlName", true);
if ((aoControls != null) && (aoControls.Length != 0))
{
Control foundControl = aoControls[0];
}
Run Code Online (Sandbox Code Playgroud)