0

您好,我想知道如何才能关注textboxesForm 中的所有内容,其中是否有任何更改的值。我在这里看到了一些代码

private void Form1_Load(object sender, EventArgs e)
{
    foreach (Control ctrl in this.Controls)
    {
        if (ctrl is TextBox)
        {
            TextBox tb = (TextBox)ctrl;
            tb.TextChanged += new EventHandler(tb_TextChanged);
        }
    }
}

void tb_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    tb.Tag = "CHANGED"; // or whatever
}

编写此代码的人说“它不能分配给 Panels 和 Grouboxes 中的文本框”。

所以我的问题是,因为我在组框或面板中几乎有每个文本框,我如何查看是否对面板或组框中的文本框进行了更改?

4

3 回答 3

8

您可以使您的方法递归:

private void Form1_Load(object sender, EventArgs e)
{
    Assign(this);
}

void Assign(Control control)
{
    foreach (Control ctrl in control.Controls)
    {
        if (ctrl is TextBox)
        {
            TextBox tb = (TextBox)ctrl;
            tb.TextChanged += new EventHandler(tb_TextChanged);
        }
        else
        {
            Assign(ctrl);
        }
    }
}

void tb_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    tb.Tag = "CHANGED"; // or whatever
}

只需为该方法找到一个更好的名称,而不是Assign.

于 2013-09-30T10:47:34.787 回答
3

当您必须处理嵌套控件时,1 for 循环无济于事。您必须使用一些递归方法或自定义stack来遍历所有控件,如下所示:

private void RegisterTextChangedEventHandler(Control root){
   Stack<Control> stack = new Stack<Control>();
   stack.Push(root);  
   Control current = null;     
   while(stack.Count>0){
      current = stack.Pop();
      foreach(var c in current.Controls){
         if(c is TextBox) ((TextBox)c).TextChanged += textChanged;
         stack.Push(c);
      }
   }
}
private void textChanged(object sender, EventArgs e){
   //....
}
//Use it
RegisterTextChangedEventHandler(yourForm);//Or your container ....
于 2013-09-30T10:40:20.663 回答
1

您需要另一个循环groupboxand panels,您可以使用以下代码:

private void addEvents(Control.ControlCollection ct)
{
    foreach (Control ctrl in ct)
    {
        if (ctrl is TextBox)
        {
            TextBox tb = (TextBox)ctrl;
            tb.TextChanged += new EventHandler(tb_TextChanged);
        }
        else if (ctrl is GroupBox || ctrl is Panel) addEvents(ctrl.Controls);
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    addEvents(this.Controls);
}

void tb_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    tb.Tag = "CHANGED"; // or whatever
}
于 2013-09-30T10:47:28.173 回答