SoFunction
Updated on 2025-03-07

Detailed explanation of the timing of dynamically adding event binding for controls in C#

Preface

I have encountered a small problem recently. I have to add the same lost focus events to dozens of text boxes. The conventional method is to add them in VS's event manager, but that is too cumbersome. You have to add dozens of text boxes dozens of times, which doesn't work.

So I thought of dynamic binding, and the first try is as follows:

foreach(TextBox tbx in tbxs){ 
   += new EventHandler(tbxN_Leave); 
} 
 
public void tbxN_Leave(object sender, EventArgs e) 
{ 
 ("Leave"); 
} 

But there is no effect. What's going on? This is what it is written online. . .

Implementation method

Check again, is it a problem with the location of the binding statement? After a closer look, I wrote the bound statement in the FormMain_Load method, so I changed my mind and wrote the bound statement into the construction method:

public FormMain() 
{ 
  InitializeComponent(); 
 
  //... 
  //Bind an event that saves countdown information at any time  foreach (TextBox tbx in tbxs) 
  { 
    += new EventHandler(tbxN_Leave); 
  } 
} 

The binding is successful and the problem is solved!

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.