c# - 在 C# 中使用按钮清除多个文本框

标签 c# winforms textbox

我使用 .NET Framework 4。

在我的表单中,我有 41 个文本框。

我试过这段代码:

private void ClearTextBoxes()
        {
            Action<Control.ControlCollection> func = null;

            func = (controls) =>
            {
                foreach (Control control in controls)
                    if (control is TextBox)
                        (control as TextBox).Clear();
                    else
                        func(control.Controls);
            };

            func(Controls);
        }

还有这段代码:

private void ClearTextBoxes(Control.ControlCollection cc)
        {
            foreach (Control ctrl in cc)
            {
                TextBox tb = ctrl as TextBox;
                if (tb != null)
                    tb.Text = String.Empty;
                else
                    ClearTextBoxes(ctrl.Controls);
            }
        }

这对我仍然不起作用。

当我尝试用这段代码清除时 TextBoxName.Text = String.Empty; 文本框成功清除但一个文本框仍然有 40 个文本框。

我该如何解决?

编辑

我把这个:

private void btnClear_Click(object sender, EventArgs e)
        {

            ClearAllText(this);

        }

void ClearAllText(Control con)
        {
            foreach (Control c in con.Controls)
            {
                if (c is TextBox)
                    ((TextBox)c).Clear();
                else
                    ClearAllText(c);
            }
        }

但还是不行。

编辑

Image

我使用面板和分离器。

最佳答案

void ClearAllText(Control con)
{
    foreach (Control c in con.Controls)
    {
      if (c is TextBox)
         ((TextBox)c).Clear();
      else
         ClearAllText(c);
    }
}

要使用上面的代码,只需这样做:

ClearAllText(this);

关于c# - 在 C# 中使用按钮清除多个文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20065408/

相关文章:

c# - 如何更改 'Add or Remove Programs'中的图标

c# - 在 ListViewItem C# 中添加多于 2 个图像

c# - 减少重复代码

c# - 在 C# 中解析负双数时出现异常

c# - 如何从控制台应用程序运行 winform?

c# - 跟随/剪辑到形状的文本?

asp.net - 仅使用 css 将标签与文本框正确对齐

c# - TextBox 水平滚动条在 Windows 窗体中无法正常工作

c# - 从 C# 应用程序执行 excel

c# - Visual Studio 和 ASP.NET Core 中的 ssl 问题