Handling all textbox event in one Handler

后端 未结 4 1907
感动是毒
感动是毒 2020-12-18 11:27

I do know how to handle event of textboxes in my form. But want to make this code shorter because I will 30 textboxes. It\'s inefficient to use this:

Private         


        
4条回答
  •  一整个雨季
    2020-12-18 11:56

    The best way would be to inherit from TextBox, override its OnTextChanged method to add your custom handling code, and then use that on your form(s) instead of the built-in TextBox control.

    That way, all of the event handling code is in one single place and you increase abstraction. The behavior follows and is defined within the control class itself, not the form that contains the control. And of course, it frees you from having a bunch of ugly, hard-to-maintain Handles statements, or worse, slow and even uglier For loops.

    For example, add this code defining a new custom text box control to a new file in your project:

    Public Class CustomTextBox : Inherits TextBox
    
        Protected Overridable Sub OnTextChanged(e As EventArgs)
            ' Do whatever you want to do here...
            MsgBox(Me.Text)
    
            ' Call the base class implementation for default behavior.
            ' (If you don't call this, the TextChanged event will never be raised!)
            MyBase.OnTextChanged(e)
        End Sub
    
    End Class
    

    Then, after you recompile, you should be able to replace your existing TextBox controls with the newly-defined CustomTextBox control that has all of your behavior built in.

提交回复
热议问题