C#遍历容器内中的控件并设置

一.一个递归方法取得页面上所有类型为textbox的控件,并对其清空,相信你看了后有所感悟。

代码
1 private void Button1_Click(object sender, System.EventArgs e)
2 {
3  foreach (Control ctl in this.Controls)
4 {
5  this.txtClear(ctl);
6 }
7 }
8  private void txtClear(Control ctls)
9 {
10  if(ctls.HasControls())
11 {
12  foreach (Control ctl in ctls.Controls)
13 {
14 txtClear(ctl);
15 }
16 }
17  else
18 {
19  if (ctls.GetType().Name == "TextBox")
20 {
21 TextBox tb = new TextBox();
22 tb = (TextBox)this.FindControl(ctls.ID);
23 tb.Text = "";
24 }
25 }
26 }
27  

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

写了:

1 foreach (Control ctrl in this.Controls)
2 {
3 if (ctrl.GetType().Name == "TextBox")
4 ctrl.Text = "";
5 }
6  

运行后TextBox内容没有清空,后来调试了下发现

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

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

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

1 foreach (Control ctrl in grboxEdit.Controls)
2 {
3 if (ctrl.GetType().Name == "TextBox")
4 ctrl.Text = "";
5 }
6

           

可以了,但这只能解决单个特定的容器。上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);

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

三.

代码
1 #region SetContainerControlEnabled
2 /// <summary>
3 /// 设定容器内控件是否可用
4 /// </summary>
5 /// <param name="parentCtrl">容器控件</param>
6 /// <param name="enabled">是否可用</param>
7 public static void SetContainerControlEnabled(Control parentCtrl, bool enabled)
8 {
9 foreach (Control ctrl in parentCtrl.Controls)
10 {
11 if (ctrl.GetType().FullName == "System.Windows.Forms.Label") continue;
12 if (ctrl.Tag != null && ctrl.Tag.ToString() == CS_EXCLUDE) continue;
13 PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(ctrl);
14 PropertyDescriptor pdReadOnly = pdc.Find("ReadOnly", false);
15 PropertyDescriptor pdEnabled = pdc.Find("Enabled", false);
16 if (pdReadOnly != null)
17 {
18 pdReadOnly.SetValue(ctrl, !enabled);
19 if (pdEnabled != null)
20 {
21 pdEnabled.SetValue(ctrl, true);
22 }
23 }
24 else
25 {
26 if (pdEnabled != null)
27 {
28 pdEnabled.SetValue(ctrl, enabled);
29 }
30 }
31 }
32 }
posted @ 2010-09-26 09:47  xfyn  阅读(3674)  评论(0编辑  收藏  举报