Assigning event TextChanged to all textboxes in Fo

2019-02-21 04:24发布

问题:

Hello I was wondering how can I keep an eye on all textboxes in Form whether in any of them was changed value. I saw some code 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
}

And a guy who wrote this code says that "it can't be assigned to textboxes in Panels and Grouboxes".

So my question is as I have almost every textbox in groubox or panel, how can I see whether change was made for textboxes in panels or groupbox?

回答1:

You can make your method recursive:

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
}

Just find a better name for the method instead of Assign.



回答2:

When you have to deal with nested controls, 1 for loop can't help. You have to use some recursive method or custom stack to loop through all the controls, something like this:

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 ....


回答3:

You need another loop for the groupbox and panels, you can use this code:

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
}