I have created a groupbox on a Windows form. It has many text boxes (ALL textbox controls). I find myself adding this event handler to each textbox. Is there a way that one event handler could be written to handle every time the user moves from textbox to textbox? Here is a sample of the current event(s) being handled which works fine.

Private Sub CustomerIDTextBox_LostFocus(sender As Object, e As System.EventArgs) Handles CustomerIDTextBox.LostFocus
        Try
            CustomerDataContext1.SubmitChanges()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

Private Sub CompanyNameTextBox_LostFocus(sender As Object, e As System.EventArgs) Handles CompanyNameTextBox.LostFocus
        Try
            CustomerDataContext1.SubmitChanges()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

Private Sub ContactNameTextBox_LostFocus(sender As Object, e As System.EventArgs) Handles ContactNameTextBox.LostFocus
        Try
            CustomerDataContext1.SubmitChanges()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
有帮助吗?

解决方案

Dim textBoxes = Me.Controls.OfType(Of TextBox)()
For Each txtbox In textBoxes
    AddHandler txtbox.LostFocus, AddressOf txtLostFocus
Next

one handler for all txtbox'es.

Private Sub txtLostFocus(sender As Object, e As System.EventArgs)

 Try
        CustomerDataContext1.SubmitChanges()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
End sub

其他提示

Like this ?:

Private Sub "Your form"(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 
MyBase.Load
    AddHandler CustomerIDTextBox.LostFocus, AddressOf DoStuff
    AddHandler CompanyNameTextBox.LostFocus, AddressOf DoStuff
    AddHandler ContactNameTextBox.LostFocus, AddressOf DoStuff
End Sub

Private Sub DoStuff(ByVal sender As Object, ByVal e As EventArgs)
    Try
        CustomerDataContext1.SubmitChanges()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top