Skip to content
Advertisement

Parameter returning not in the correct format

I have an async task method that queries a database table for the total amount of Credits in a specific column. I have a string parameter in the method that I use for the query to identify which user is logged in, which is stored in Properties.Settings.Default.Student_Number;. The column for the student number in the database is a varchar and everywhere else in my code its a string, but I’m getting an exception saying Input string was not in correct format. Any idea what I’m doing wrong

How I am calling the method

I am using binding on the label for

Advertisement

Answer

The result returned by ExecuteScalar will either be an int or be null. Also, making a round-trip via string is not necessary. But we must check for null.

Pattern matching was introduced in recent versions of C#, allowing terser code in many situations:

If the scalar is a boxed int object, it will be cast to int and assigned to the new variable i and the result of the is expression will be true. We use this result in a ternary expression to determine the final result.


Yet another possibility:

The operator as casts the input to the desired type if the cast is successful and otherwise returns null. Therefore the target type must be nullable. Hence we specify int? (= Nullable<int>) as target type. We use the null coalescing operator ?? to convert null to 0.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement