今天一同学问我怎么样可以遍历页面中的textbox ,我一直记得是页面有个什么控件的结合,直接遍历一下就可以获得,就直接告诉他了。
后来想想还是自己做一遍比较好,发现了点小问题,直接用for循环怎么也遍历不到。最后调试才发现,一个for循环只能遍历最外边一层的控件,要想全部获得就要使用递归,贴出测试代码:
protected void Button1_Click(object sender, EventArgs e)
{
ClearControl(this.Controls);
}
protected void ClearControl(ControlCollection ct)
{
foreach (Control ctl in ct)
{
if (ctl is TextBox)
{
TextBox t = (TextBox)ctl;
t.Text = string.Empty;
}
if (ctl.HasControls())
{
ClearControl(ctl.Controls);
}
}
}
上边是.net里面的,顺便把winform中的遍历控件的方法也贴出来,防止以后再忘了:
foreach (System.Windows.Forms.Control control in this.Controls)
{
if (control is System.Windows.Forms.TextBox)
{
System.Windows.Forms.TextBox tb = (System.Windows.Forms.TextBox)control ;
tb.Text = String.Empty ;
}
}