本例以获取web窗体上所有的TextBox为例加以说明: foreach (Control c in Page.Controls) { if (c is TextBox) {
} }
采用上述方法不能获得所有控件,它只能获得页面上一级控件,如果某个控件还有子控件,将不能获得。
可以采用下述方法:
1、 static ArrayList al = null; // 存放TextBox控件
2、初始化:
if (!Page.IsPostBack) { al = new ArrayList(); }
3、 定义方法:(使用c.HasControls()判断是否有子控件)
private void GetTextBox(Control ctrl) { foreach (Control c in ctrl.Controls) { if (c is TextBox) { al.Add(c); } else if (c.HasControls()) { GetTextBox(c); } } }
4、调用
protected void Button1_Click(object sender, EventArgs e) { GetTextBox(this); }
protected void Button2_Click(object sender, EventArgs e) { for (int i = 0; i < al.Count; i++) { this.Label1.Text += ((TextBox)al[i]).Text; } }
