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
Dim Id As String = IdBox.Text
' Indicate that the keypress is handled.
e.Handled = True
Try
' Create a new widget in the widget collection.
widgets.Add(newWidgetKey, New Widget(IdBox.Text))
Catch ex As AlreadyInUseException
' Exception if ID is already in use.
' Ask the user if they would like to cancel the ID already in use .
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()
widgets.Remove(widgetKey)
Next
End If
Try
' Try creating the new widget in the widget collection again.
widgets.Add(newWidgetKey, New Widget(IdBox.Text))
Catch exRe As Exception
' If there were still exceptions, make the user start again.
MessageBox.Show("Still could not use that Id" + vbNewLine + _
exRe.Message, "Id could not be used", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
Else
' If the user wishes to try another Id instead,
' Select the text in the Id box, ready for attempting a new Id.
IdBox.SelectAll()
Exit Sub
End If
Catch ex As Exception
' Exception if .Add() failed or New() failed for unknown reason - This should never happen.
MessageBox.Show("Id validation failed for an unknown reason." + vbNewLine + _
"Please try again.","Id validation failed")
IdBox.SelectAll()
Exit Sub
End Try
End If
End Sub