2013-11-21 124 views
0

我想清除所有文本框。写的公共职能为:无法清除文本框

public void clean(Control parent) 
{ 
    try 
    { 
     foreach (Control c in parent.Controls) 
     { 
      TextBox tb = c as TextBox; //if the control is a textbox 
      if (tb != null)//Will be null if c is not a TextBox 
      { 
       tb.Text = String.Empty;//display nothing 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine("{0} Exception caught.", ex); 
    } 
} 
在类页面

我希望它被称为我宣布:

PublicFunctions pubvar = new PublicFunctions(); 

,我把它作为

pubvar.clean(Page); 

,但它不是工作......甚至没有发生错误...我的文本框不清除...帮助?

+0

何时何地你打了吗?另外,你在这里使用异常处理是毫无意义的。 – James

+0

什么是页面的类型?你发送什么函数? – user2857877

+0

@James即时关闭我的连接到数据库后,我做了一个GridView绑定后调用它。所有这一切发生时,我点击保存提交信息...也是没有意义的?请解释。 – New2This

回答

0

您应该使用递归循环来检查所有控件。

试试这个代码

using System; 
using System.Collections.Generic; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public class PublicFunctions 
{ 
    public void Clean(Control parent) 
    { 
     var controls = GetAllControls(parent); 

     foreach (Control c in controls) 
     { 
      TextBox tb = c as TextBox; 
      if (tb != null) 
      { 
       tb.Text = String.Empty; 
      } 
     } 
    } 

    public IEnumerable<Control> GetAllControls(Control parent) 
    { 
     foreach (Control control in parent.Controls) 
     { 
      yield return control; 

      foreach (Control innerControl in control.Controls) 
      { 
       yield return innerControl; 
      } 
     } 
    } 
} 
+0

只是试了一下。这仍然不是清除文本框...我不知道为什么... – New2This

+0

你有这个代码的任何错误? –

+1

这不会解决任何问题,OP的代码应该可以工作。 – James