【问题标题】:having trouble clearing textboxes无法清除文本框
【发布时间】:2013-12-06 00:45:34
【问题描述】:

我想清除所有文本框。将公共函数写为:

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);

但它不起作用...甚至没有抛出错误...而且我的文本框没有清除...帮助?

【问题讨论】:

  • 您在何时何地调用它?此外,您在这里使用异常处理是没有意义的。
  • 什么是页面类型?你送什么给功能?
  • @James 我在关闭与数据库的连接后并在我执行 gridview 绑定后调用它。当我单击保存以提交信息时,这一切都会发生……而且这毫无意义吗?请解释一下。
  • 这毫无意义,因为 1. 您正在吞下异常,并且 2. 如果在该代码块期间抛出异常,则 从根本上说 是错误的 - 你不想吞下去。您是否在其他任何地方填充您的 UI?在我看来,您在回发后重新填充它。

标签: textbox public-method


【解决方案1】:

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

试试这个代码

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;
            }
        }
    }
}

【讨论】:

  • 这不会解决任何问题,OP 的代码应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
相关资源
最近更新 更多