"does not work" is not very helpful in describing a problem. TryParse does work. And "Input string is not in correct format" is not an answer. What is the value of the string that you are trying to convert?

3 solutions

Solution 1

If you are going to use the Convert.ToInt32 method then you need to wrap that call in a try-catch so that you can capture and deal with that exception.
The better and more preferred ways would be to use the Int32.Parse or TryParse methods as Wes has alluded to in his comment.

The basic concept to learn here is that all user input should be treated as though it is evil. Validate the hell out of it and make sure that you can catch as many eventualities as you can and deal with them appropriately.

[Update]: The reasons for the exception to occur in the Convert.ToInt32 scenario are plenty. If the textbox value is empty or if the textbox value contains anything other than just 0 through 9 then this exception will occur. The idea of the try catch is to provide a graceful handling of the error.

Of course the error will still occur because the input in the textbox cannot be converted into a number. The try-catch will just give you the opportunity of applying a default value or letting the user know in a graceful way.