1
double mrp = Convert.ToDouble(gvRow.Cells[9].Text.ToString());

In the above code when mrp = "6458.0" it works fine but somtimes when mrp is empty now it throws an exception.kindly help me to solve this issue....

coder
  • 1,980
  • 3
  • 21
  • 32
Sathya
  • 59
  • 1
  • 10
  • 4
    What should an empty string be converted to? Where is the common sense in the approach to this question? Did you try putting an `if` there to check if it is an empty string? _And why not?_ – ppeterka Apr 02 '13 at 10:32

7 Answers7

1

Use Double.TryParse, this will not throw an exception and if the parsing fails then you will get 0 as the parsed value.

double number;
if (double.TryParse(gvRow.Cells[9].Text, out number))
{
    //valid
}
{
    //invalid
}

//if invalid then number will hold `0`
Habib
  • 219,104
  • 29
  • 407
  • 436
1

Use Double.TryParse to check if the conversion succeeds or not.

double mrp;
if (Double.TryParse(gvRow.Cells[9].Text.ToString(), out mrp))
{
   // Success
}
else
{
  // Cannot convert to double
}

Also, You might want to use Double.IsNan

Blachshma
  • 17,097
  • 4
  • 58
  • 72
1

you should try this: double mrp = gvRow.Cells[9].Text.ToString() != "" ? Convert.ToDouble(gvRow.Cells[9].Text.ToString()): 0.0;

Phong Vo
  • 1,078
  • 7
  • 16
0
if (Double.TryParse(gvRow.Cells[9].Text.ToString(), out mrp))
   Console.WriteLine("Ok");
else
   Console.WriteLine("not a number");
Lefteris E
  • 2,806
  • 1
  • 24
  • 23
0

You can use double.Tryparse..

 double num; 

if(Double.Tryparse(gvRow.Cells[9].Text.ToString(),num) 
{
  // get the converted value
}
else
{
  //invalid
}
coder
  • 1,980
  • 3
  • 21
  • 32
  • It's not a good answer. It doesn't change anything. How can it convert something like "HEY" to double? It'll throw an exception again. – Anıl Canlı Apr 02 '13 at 10:39
0

You should use Double.TryParse as others talked about.

But as an alternative way, you can validate your cells by data type checking, or it shouldn't be null etc.

Anıl Canlı
  • 432
  • 9
  • 20
0

Try double.tryParse

Reference

Convert.ToDouble will throw an exception on non-numbers
Double.Parse will throw an exception on non-numbers or null
Double.TryParse will return false or 0 on any of the above without generating an exception.
Community
  • 1
  • 1
Amit
  • 15,217
  • 8
  • 46
  • 68