将事件TextChanged分配给Form中的所有文本框

时间:2013-09-30 10:30:59

标签: c# .net winforms textbox

您好我想知道如何关注Form中的所有textboxes是否在其中任何一个都被更改了值。我看到了一些代码here

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中的文本框”。

所以我的问题是因为我几乎每个文本框都在地图集或面板中,我怎样才能看到是否对面板或组合框中的文本框进行了更改?

3 个答案:

答案 0 :(得分:6)

您可以使您的方法递归:

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

答案 1 :(得分: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 ....

答案 2 :(得分:1)

您需要groupboxpanels的其他循环,您可以使用以下代码:

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
}