日期:2014-05-17  浏览次数:20946 次

C#遍历容器内中的控件

准备是将Form中所有的TextBox控件的Text属性的文本清空

写了: foreach (Control ctrl in this.Controls)
??????????? {
??????????????? if (ctrl.GetType().Name == "TextBox")
??????????????????? ctrl.Text = "";
??????????? }
运行后TextBox内容没有清空,后来调试了下发现

并没有遍历TextBox控件,Form中其它的控件都遍历了,

感觉奇怪怎么没有遍历TextBox控件,发现自己的TextBox

控件再容器控件GroupBox内,问了下QQ好友他说再容器内遍历

??????????? foreach (Control ctrl in grboxEdit.Controls)
??????????? {
??????????????? if (ctrl.GetType().Name == "TextBox")
??????????????????? ctrl.Text = "";
??????????? }

可以了,但这只能解决单个特定的容器。上Google搜了下找的了

csdn一篇关于用递归遍历容器中的控件的文章,方法是:
private void OperateControls(Control control)?
{?
??? foreach(Control c in control.Controls)?
??? {?
?????????? if(c is Panel)?
??????? {?
???????????? OperateControls(c);?
??????? }?
??????? if(c is GroupBox)?
????????? {?
???????????? OperateControls(c);?
?????? }?
?????? if(c is TextBox)?
???????? {?
????????? // 它是 TextBox, 要干什么随便你?
????????? }?
?? }?
}?
调用时用:?
OperateControls(this);

这样就可以遍历容器中的控件了,呵呵。