I am trying to convert a string to an integer.
The code used is;Dim PStab As Integer
PStab = Convert.ToInt32(P1Stab1.Text)
P1Stab1 is a label.
When I load the form I get this error;
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
In another subroutine I have used Convert.ToInt32() with no problems to convert the contents of 18 labels to integer (including Convert.ToInt32(P1Stab1.Text)) so I can add them together. The code used is;
Public PlayersTotal As Integer
PlayersTotal = Convert.ToInt32(P1Stab1.Text) + Convert.ToInt32(P1Stab2.Text) + Convert.ToInt32(P1Stab3.Text) + Convert.ToInt32(P1Stab4.Text) + Convert.ToInt32(P1Stab5.Text) + Convert.ToInt32(P1Stab6.Text) + Convert.ToInt32(P1Stab7.Text) + Convert.ToInt32(P1Stab8.Text) + Convert.ToInt32(P1Stab9.Text) + Convert.ToInt32(P1Stab10.Text) + Convert.ToInt32(P1Stab11.Text) + Convert.ToInt32(P1Stab12.Text) + Convert.ToInt32(P1Stab13.Text) + Convert.ToInt32(P1Stab14.Text) + Convert.ToInt32(P1Stab15.Text) + Convert.ToInt32(P1Stab16.Text) + Convert.ToInt32(P1Stab17.Text) + Convert.ToInt32(P1Stab18.Text)
So can anyone help with what is going wrong?
Note: At the time of loading the form the labels are defaulted to 0(zero)
解决方案The text coming back from the label is not convertible to an integer. It's that simple.
There are some major problems with your design. The first of which is why are you converting the text in a LABEL, which should be static content, to a value? Why are you not using a data model to hold this information instead? You should not be transferring data from one piece of code to another through a visual control!
You need to have a data structure in your code that manages and maintains your data and its state. Think of UI controls as a one-way medium to display that state to the user. They are NOT to be used to transfer data or state information. This makes maintaining the data difficult to maintain and debug.
The other big problem is that Convert has some strict rules on what it will and will not convert to an Integer. If you've got a comma in there or a decimal point or a current symbol, it'll fail. Use Integer.TryParse instead.
Whatever is in "P1Stab1.Text" can't be converted to an integer. If you say what is in P1Stab1.Text then someone might be able to suggest a reason why, or if you use the debugging tools you might be able to work out why yourself, but we can't access your system so can't look for you.
It's simple: your user typed wrong.
Convert.ToInt32 tries to convert eth string, but if it finds "Hello", "123?", or "6.7" if can't convert it to an integer values, so it throws an exception.
Instead of using Convert, use Integer.TryParse:
Dim PStab As Integer
If Not Integer.TryParse(P1Stab1.Text, PStab) Then
'Report problem to user
...
Return
End If