Assigning event TextChanged to all textboxes in Form

后端 未结 3 1777
一个人的身影
一个人的身影 2020-12-11 14:11

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 voi         


        
3条回答
  •  情深已故
    2020-12-11 14:45

    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 stack = new Stack();
       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 ....
    

提交回复
热议问题