遍历页面上所有TextBox,并赋值为String.Empty(Asp.Net和WinForm)
Posted on 2010-12-15 11:14 Sky_KWolf 阅读(8937) 评论(0) 编辑 收藏 举报一、遍历窗体控件
1.普通页面遍历TextBox控件清空的方法,其他控件类似 foreach(Control c in this.controls) { if(c is TextBox) { TextBox tb=(TextBox)c; tb.Text=String.empty; } } //或 foreach (Control col in this.Controls) { if (col.GetType().Name.Equals("TextBox")) { ((TextBox)col).Text = String.empty; } }
二、遍历Asp.net页面
//不含母板页 foreach (System.Web.UI.Control txtobj in this.Page.Controls) { if (txtobj.GetType().Name .Equals("TextBox")) { // ((TextBox)txtobj).Text = String.Empty;//这是第一种方法赋值,第二种在下面 TextBox tb = new TextBox(); tb = (TextBox)this.FindControl(txtobj.ID); tb.Text = String.Empty; } }
包含母板页
//套用母版页的页面遍历TextBox控件的方法,其他控件类似 foreach (Control cp in Page.Controls) { foreach (System.Web.UI.Control ct in cp.Controls) { if (ct is HtmlForm) { foreach (Control con in ct.Controls) { foreach (Control c in con.Controls) { if (c is TextBox) { (c as TextBox).Text = String.Empty; } } } } } }
三、清除控件内容
// 清空指定页面上所有的控件内容 //public static void ClearAllContent() //清空指定页面上所有的控件内容 //包括TextBox,CheckBox,CheckBoxList,RadioButton,RadioButtonList。不过不清 //除如ListBox,DropDownList,因为这样的控件值对当前页面来说还能用,一般这些控件里都是保存的字典数据。 //<param name="page"> 指定的页面</param> public static void ClearAllContent(System.Web.UI.Control page) { int nPageControls = page.Controls.Count; for (int i = 0; i < nPageControls; i++) { foreach (System.Web.UI.Control control in page.Controls[i].Controls) { if (control.HasControls()) { ClearAllText(control); } else { if (control is TextBox) (control as TextBox).Text = ""; if (control is CheckBox) (control as CheckBox).Checked = false; if (control is RadioButtonList) (control as RadioButtonList).SelectedIndex = -1; if (control is RadioButton) (control as RadioButton).Checked = false; if (control is CheckBoxList) { foreach (ListItem item in (control as CheckBoxList).Items) { item.Selected = false; } } }//if..else }//foreach }//for }