Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate all textbox controls on a form with the same event handler

Tags:

vb.net

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.

like image 733
aphoria Avatar asked Oct 07 '08 18:10

aphoria


1 Answers

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.

like image 195
MusiGenesis Avatar answered Oct 04 '22 21:10

MusiGenesis