0

我有一个 winforms 应用程序,它必须从不同选项卡和面板中的 50 个文本框中提取文本。到目前为止,我一直无法找到有效的东西。我试过了:

foreach (Control x in this.Controls)
{
    if (x is NumericTextBox)
    {
       s = i.ToString() + ", " + ((NumericTextBox)x).Text;
       Append_to_Template_File(s);
       i++;
    }
} 

但这仅通过表单上的文本框我也找到了这个答案,但是我没有设法使它工作: 循环文本框 最佳答案导致许多错误:

  1. 非泛型声明不允许使用约束
  2. 找不到类型或命名空间名称“TControl”

我是使用 C# 的新手,我不太确定如何解决第一个错误。如果有帮助,我正在使用 Visual Studio 2008 和 .NET 3.5 有什么建议吗?

4

3 回答 3

3

您可以使用这样的方法来遍历整个控件树,而不仅仅是顶层,以获取所有控件,一直向下:

public static IEnumerable<Control> GetAllChildren(Control root)
{
    var stack = new Stack<Control>();
    stack.Push(root);

    while(stack.Any())
    {
        var next = stack.Pop();
        foreach(Control child in next.Controls)
            stack.Push(child);
        yield return next;
    }
}

然后,您可以过滤掉您想要的类型并将它们分别映射到它们的文本值:

var lines = GetAllChildren(form)
    .OfType<NumericTextBox>()
    .Select((textbox, i) => string.Format("{0}, {1}", i, textbox.Text));

foreach(var line in lines)
    Append_to_Template_File(line);
于 2013-09-20T16:56:07.627 回答
3

类似于Servy的想法。这是另一个实现;)

下面的函数获取一个控件作为参数,并返回其中所有文本框的列表作为 ref 参数 l;

 void findall(Control f, ref List<Control> l) {
        foreach (Control c in f.Controls) {
            if (c is TextBox)
                l.Add(c);
            if  (c.HasChildren)
                findall(c, ref l);
        }
    }

你可以这样称呼它

列表 l = 新列表();

findall(this, ref l);

于 2013-09-20T17:47:34.997 回答
0

递归是你的朋友!

 private void DoThings()
 {
  MyFunc(this.Controls);
 }

 private void MyFunc(Control.ControlCollection controls)
 {
      foreach (Control x in this.Controls)
      {
          if (x is NumericTextBox)
          {
             s = i.ToString() + ", " + ((NumericTextBox)x).Text;
             Append_to_Template_File(s);
             i++;
          }

          if (x.HasChildren)
              MyFunc(x.Controls)
      }
 }
于 2013-10-16T20:33:25.417 回答