VB 2008.
I have several text boxes on a form and I want each of them to use the same event handler. I know how to manually wire each one up to the handler, but I'm looking for a more generic way so if I add more text boxes they will automatically be hooked up to the event handler.
Ideas?
EDIT: Using the C# sample from MusiGenesis (and with the help of the comment left by nick), I wrote this VB code:
Private Sub AssociateTextboxEventHandler()
For Each c As Control In Me.Controls
If TypeOf c Is TextBox Then
AddHandler c.TextChanged, AddressOf tb_TextChanged
End If
Next
End Sub
Thanks a lot! SO is great.
Do something like this in your form's load event (C#, sorry, but it's easy to translate):
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
}
It's not properly recursive (it won't find text boxes on panels, for example), but you get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With