I am working on my first real WinForms application using VB.NET and the project is getting a little bigger than originally expected - so I'm more or less forced to deal with the challenge of structuring my code a little better. I'm not used to doing this in WinForms so I'm not sure if the solution that I found is the right way to do it:
Since I have a lot of Control elements, especially TextBoxes, I really need to move the code for handling different events to another class. As far as I've seen, there are many different ways how to do this, depending on what kind of program you're working on. The one I found the easiest to understand is creating an additional class and declaring all the necessary Control objects using WithEvents. So for example in my main class I would have:
Private Sub txtCustomerName_TextChanged(sender As Object, e As EventArgs) Handles txtCustomerName.TextChanged
' do lots of stuff here
End Sub
and if instead I want to move all that code to my new class, it would look something like this:
Public Class Events
Public WithEvents txtCustomerName As TextBox
Public Sub New()
End Sub
Private Sub txtCustomerName_TextChanged(sender As Object, e As EventArgs) Handles txtCustomerName.TextChanged
' do lots of stuff here...
End Sub
End Class
meaning that all I would have to do in my main class now would be:
Dim events As New Events()
events.txtCustomerName = txtCustomerName
and do this for all the other Control elements as well. That way, I could keep my main class a lot cleaner but I would end up with a huge class full of event listener code. I feel like this would help me a little bit but it still feels kind of crude. My next idea would be to maybe split this up further so I could have one event class for TextBox events and another one for Button events - but then again I'm not even sure if I'm on the right way here or if I'm missing something entirely.