Are you in the habit of putting a lot of code in your Event Handlers? Use Extract Method Refactoring to move that code to a real method. We all know that it is not a good practice to have a lot of code in Event Handlers, and that the preferred methodology is to call a real method from the event handler to do the work.
The problem is that many of us got into the habit of coding large blocks of code in the Event Handler. Now, it can be a pain to move that code to a real method. In Refactoring lingo, that's called Extract Method. With NET Refactor's Extract Method feature, it is a snap. Figure 1 shows an event handler that has a lot of code that I want to move to a new method.
Figure 1 - Event Handler With Code.
| Private Sub btnOk_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnOk.Click Try Dim sPath As String = _ Replace(Me.tvDirectoryList.SelectedNode.FullPath, "\\", "\") Dim i As Integer With Me.lvwFileList Dim j As Integer = .SelectedItems.Count - 1 ReDim FN(j) For i = 0 To j FN(i) = sPath & "\" & .SelectedItems.Item(i).Text Next End With Me.Close() DoEvents() Catch ex As System.Exception StructuredErrorHandler(ex) End Try End Sub |

| Private Sub btnOk_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnOk.Click BuildArrayAndCloseForm() End Sub Private Sub BuildArrayAndCloseForm() Try Dim sPath As String = _ Replace(Me.tvDirectoryList.SelectedNode.FullPath, "\\", "\") Dim i As Integer With Me.lvwFileList Dim j As Integer = .SelectedItems.Count - 1 ReDim FN(j) For i = 0 To j FN(i) = sPath & "\" & .SelectedItems.Item(i).Text Next End With Me.Close() DoEvents() Catch ex As System.Exception StructuredErrorHandler(ex) End Try End Sub |

| Private Sub btnOk_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnOk.Click BuildArrayAndCloseForm() End Sub ' This is where BuildArrayAndCloseForm used to be... Private Sub lvwFileList_SelectedIndexChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles lvwFileList.SelectedIndexChanged btnOk.Enabled = (lvwFileList.SelectedItems.Count > 0) End Sub |
| #Region " Private Methods " Private Sub BuildArrayAndCloseForm() Try Dim sPath As String = _ Replace(Me.tvDirectoryList.SelectedNode.FullPath, "\\", "\") Dim i As Integer With Me.lvwFileList Dim j As Integer = .SelectedItems.Count - 1 ReDim FN(j) For i = 0 To j FN(i) = sPath & "\" & .SelectedItems.Item(i).Text Next End With Me.Close() DoEvents() Catch ex As System.Exception StructuredErrorHandler(ex) End Try End Sub #End Region |