Results 1 to 4 of 4

Thread: [RESOLVED] Call event handler sub

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Resolved [RESOLVED] Call event handler sub

    Hi Folks

    I have an TextBox.KeyPress event handler sub that essentially does the following
    VB Code:
    1. Private Sub IdBox_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles IdBox.KeyPress
    2.         ' Handle any "Enter"-key presses in the Id TextBox when the entered text length is greater than 0.
    3.  
    4.         If Asc(e.KeyChar) = Keys.Enter And IdBox.Text.Length > 0 Then
    5.             Dim Id As String = IdBox.Text
    6.  
    7.             ' Indicate that the keypress is handled.
    8.             e.Handled = True
    9.  
    10.             Try
    11.                 ' Create a new widget in the widget collection.
    12.                 widgets.Add(newWidgetKey, New Widget(IdBox.Text))
    13.  
    14.             Catch ex As AlreadyInUseException
    15.                 ' Exception if ID is already in use.
    16.                 ' Ask the user if they would like to cancel the ID already in use .
    17.                 Dim userReply As DialogResult = MessageBox.Show("Could not use that ID as it is listed as being already in use." _
    18.                                                                 + vbNewLine + "Would you like to cancel the currentID?", _
    19.                                                                 "ID in use", MessageBoxButtons.YesNo, MessageBoxIcon.Error, _
    20.                                                                 MessageBoxDefaultButton.Button2)
    21.  
    22.                 If userReply = Windows.Forms.DialogResult.Yes Then
    23.                     ' If the user wishes to cancel the ID,
    24.                     ' list the widgets with that ID from the collection of current widgets.
    25.                     Dim duplicateWidgets = (From widget In widgets
    26.                                          Where widget.Value.Id = IdBox.Text
    27.                                          Select widget.Key).ToList
    28.                     ' Check if the list has any items.
    29.                     If duplicateWidgets.Count > 0 Then
    30.                         ' Cancel each listed widget.
    31.                         For Each widgetKey As UInteger In duplicateWidgets
    32.                             widgets.Item(widgetKey).CancelWidget()
    33.                             widgets.Remove(widgetKey)
    34.                         Next
    35.                     End If
    36.  
    37.                     Try
    38.                         ' Try creating the new widget in the widget collection again.
    39.                         widgets.Add(newWidgetKey, New Widget(IdBox.Text))
    40.                     Catch exRe As Exception
    41.                         ' If there were still exceptions, make the user start again.
    42.                         MessageBox.Show("Still could not use that Id" + vbNewLine + _
    43.                                         exRe.Message, "Id could not be used", _
    44.                                         MessageBoxButtons.OK, MessageBoxIcon.Error)
    45.                         Exit Sub
    46.                     End Try
    47.                 Else
    48.                     ' If the user wishes to try another Id instead,
    49.                     ' Select the text in the Id box, ready for attempting a new Id.
    50.                     IdBox.SelectAll()
    51.                     Exit Sub
    52.                 End If
    53.  
    54.             Catch ex As Exception
    55.                 ' Exception if .Add() failed or New() failed for unknown reason - This should never happen.
    56.                 MessageBox.Show("Id validation failed for an unknown reason." + vbNewLine + _
    57.                                 "Please try again.","Id validation failed")
    58.                 IdBox.SelectAll()
    59.                 Exit Sub
    60.             End Try
    61.  
    62.         End If
    63.     End Sub

    In plain English, the user enters and ID into the TextBox and presses the enter key, the event handler tries to create a widget with that ID, but will fail if there is already another one with the same ID.
    The user then is presented with a choice, cancel the older widget and continue creating the new one, or try another ID.
    If they chose to cancel the old one and continue creating the new one, the handler has to try again... Except this leads to a nested Try (of which I'm not fond) which essentially does the same thing the preceding code just did...

    Is there a way I can remove the nested Try and just call the Handler again here? Or is there a better way of handling the situation altogether?
    This would mean that the nested Try exception could also be handled more gracefully

    I could leave it as is, but I have this situation cropping up in other places as well so would like to find a neater way of doing it
    Thanks
    Last edited by wolf99; Aug 19th, 2013 at 05:27 AM.
    Thanks

  2. #2
    Hyperactive Member
    Join Date
    Jan 2002
    Location
    UK, Suffolk
    Posts
    319

    Re: Call event handler sub

    You could create a function to process the widgets being added and then return a status to the key press event.

    I created this very quickly to give you a basic idea.


    Code:
    Enum WidgetResultEnum
            ADDED
            ALREADYINUSE
            RETRY
            CANCELLED
        End Enum
    
      Private Function AddNewWidget(_strValue As String) As WidgetResultEnum
            Try
                ' Create a new widget in the widget collection.
                widgets.Add(newWidgetKey, New Widget(_strValue))
                Return WidgetResultEnum.ADDED
            Catch ex As AlreadyInUseException
                Dim userReply As DialogResult = MessageBox.Show("Could not use that ID as it is listed as being already in use." _
                                                                   + vbNewLine + "Would you like to cancel the currentID?", _
                                                                   "ID in use", MessageBoxButtons.YesNo, MessageBoxIcon.Error, _
                                                                   MessageBoxDefaultButton.Button2)
                If userReply = Windows.Forms.DialogResult.Yes Then
                    ' If the user wishes to cancel the ID,
                    ' list the widgets with that ID from the collection of current widgets.
                    Dim duplicateWidgets = (From widget In widgets
                                         Where widget.Value.Id = IdBox.Text
                                         Select widget.Key).ToList
                    ' Check if the list has any items.
                    If duplicateWidgets.Count > 0 Then
                        ' Cancel each listed widget.
                        For Each widgetKey As UInteger In duplicateWidgets
                            widgets.Item(widgetKey).CancelWidget()
                        Next
                        Return WidgetResultEnum.RETRY
                    End If
    
                ElseIf userReply = Windows.Forms.DialogResult.No Then
                    ' If the user wishes to try another Id instead,
                    ' Select the text in the Id box, ready for attempting a new Id.
                    Return WidgetResultEnum.CANCELLED
                End If
    
    
            End Try
        End Function
    
    Private Sub IdBox_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles IdBox.KeyPress
     ' Handle any "Enter"-key presses in the Id TextBox when the entered text length is greater than 0.
    
            If Asc(e.KeyChar) = Keys.Enter And IdBox.Text.Length > 0 Then
                Do While Me.AddNewWidget(IDBox.Text) = WidgetResultEnum.RETRY
                    ' Loop until the result is valid
                Loop
    
                Messagebox.Show("Loop Ended")
    
            End If
    
        End Sub

  3. #3
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Call event handler sub

    I guess the question you're really asking is whether other functions and subs 'outside' the Try/Catch structure as such come under its protection to which the answer is they most certainly do. So there is no reason not to do what you always do with repeated code and create a separate sub or function.
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,043

    Re: Call event handler sub

    Using exception handling to catch exceptions is ALWAYS slow. Therefore, whenever possible, check for the failing situation explicitly rather than relying on an exception being thrown. This is an excellent case of that. The Widget appears to be a Dictionary, and if it is not, it certainly could be. The Dictionary has a method called ContainsKey. Therefore, you can get rid of the exception handling with this construct:

    Code:
    If widgets.ContainsKey(newWidgetKey) Then
     'The key is already in there, do something else
    Else
     'Add the widget
    End If
    This will have noticeably better performance because exception catching can be slow enough to see it.

    As a rule, if the problem isn't exceptional, but can be predicted, then do so. In this case, you can determine whether or not the addition will fail by checking to see whether or not the dictionary already contains the key.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width