Reputation: 15
I am using the following as a workaround:
Public Sub ClearTextBox(ByVal root As Control)
For Each ctrl As Control In root.Controls
ClearTextBox(ctrl)
If TypeOf ctrl Is TextBox Then CType(ctrl, TextBox).Text = 0
If TypeOf ctrl Is ComboBox Then CType(ctrl, ComboBox).Text = String.Empty
Next ctrl
End Sub
the reason i am setting the textboxes to 0 is because when I set String.Empty, one text box (containing only Int16) throws a conversion error. anyone help on stopping the error or just ignoring that one textbox?
As per Andrews response, I ran the code again, and i get the following:
+ $exception {"Conversion from string """" to type 'Short' is not valid."} System.InvalidCastException
The code highlighted is:
Dim age As Int16 = Txt_CharAge.Text
Please bear with me a little, I am totally new to this and am completely self taught. If you need further code to help, just let me know. Thanks
Upvotes: 1
Views: 258
Reputation: 25066
When you have a line such as
Dim age As Int16 = Txt_CharAge.Text
you are telling the computer to put a string into a number. Without Option Strict On, it is free to make up any way it likes of stuffing a string (which is not an Int16) into an Int16. You have given up your control of what is happening at that point.
The better way is to tell it how to convert the characters of the text into a number. (See The Treachery of Images for an explanation that a representation of some thing is not that thing.)
There is a ready-made set of methods named TryParse
for many of the built-in types.
So, instead of
Dim age As Int16 = Txt_CharAge.Text
you should have
Dim age As Integer
Integer.TryParse(Txt_CharAge.Text, age)
The TryParse
methods are actually functions which return True
if the parse was successful, otherwise they return False
(and set the variable to its default value), but in this case it appears that you don't need to know if the parse succeeded because the default value of 0 for an Integer will suffice.
Note that there isn't really a need to use an Int16 instead of an Integer unless you know why you need to add the complication of using an Int16 instead of an Integer.
Upvotes: 2