Input string was not in a correct format.
I am trying to convert a null value to a double value using convert function in C#. Can anybody help me in this regards...
I am getting a null value in a variable named "gridCol1"
Step 1 - I am doing
Convert.ToDouble ( gridCol1.ToString() );
Error : "Input string was not in a correct format."
You can't convert a null value to a meaningful value through Convert. Your best option is to check for null first and then assign a value of 0 (or whatever) to the result (whereever Convert was sending its results too).
However looking at your code you might not be getting a null value. What is the type of gridCol1? If it is a DataGridViewCell then it will probably return the type to you in ToString(). You need to get the Value property instead. If gridCol1 represents the actual value then your code is correct.
if (gridCol1 != null)
result = Convert.ToDouble(gridCol1); //Don't really need to call ToString()
else
result = 0.0;
The short form (when you want an expression) is:
result = (gridCol1 != null) ? Convert.ToDouble(gridCol1) : 0.0;
Personally I have run across this situation so much that I wrote a custom utility class called Converter that emulates Convert but handles null and a few other sundry values. This simplifies my code greatly. Even better is that if I truly want to blow up when getting a null value then I need only change back to Convert.
Michael Taylor - 8/3/06