I'm currently trying to code a program that interfaces with USB devices based on their serial number. I have it partially working such that it will accept proper serial numbers in the textbox but if anything but an integer is put into the box it will throw and error. How can I fix this? So far I've been unsuccessful in trying to work around this. In a nutshell, I want the program to read the 5 digit serial from the textbox and try to connect, and if anything other than an integer is added, it'll simply throw a message to the user saying the serial isn't correct. Here's what I have so far.
'Declares an integer to be used for custom serial numbers incase phidgets need to be swapped.
Dim MC1Serial As Integer
'Throws error if there's no real serial in the corresponding box.
If TextSerial1.Text = 0 Then
MsgBox("Please ensure you have a proper serial numbers in the textbox, and not 0")
Else
MC1Serial = TextSerial1.Text
End If
'Creates a new instance of a MC for the first controller.
MC1 = New Phidget21COM.PhidgetMotorControl
'Attempts to attach phidget and either checks the box or throws an error.
MC1.Open(MC1Serial)
MC1.WaitForAttachment(1000)
If MC1.IsAttached = True Then
CheckMC1.Checked = True
'Enables the timer to allow the position of the buttons to update accordingly.
TimerJoysticks.Enabled = True
Else
MsgBox("There was a problem finding MC1. Check connections and settings.")
End If
There are many things you can do. Val Function is one of them. You can also use IsNumeric to check wether the whole input string is actually a number.
If Not IsNumeric(TextSerial1.Text) or Val(TextSerial1.Text) = 0 Then
MsgBox("Please ensure you have a proper serial numbers in the textbox, and not 0")
' You should exit the sub here so that the code doesn't continue.
Else
MC1Serial = CInt(TextSerial1.Text)
End If