Sathya
Sathya

Reputation: 59

how to convert empty string to double

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....

Upvotes: 1

Views: 8128

Answers (7)

coder
coder

Reputation: 2000

You can use double.Tryparse..

 double num; 

if(Double.Tryparse(gvRow.Cells[9].Text.ToString(),num) 
{
  // get the converted value
}
else
{
  //invalid
}

Upvotes: 0

Amit
Amit

Reputation: 15387

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.

Upvotes: 0

Anıl Canlı
Anıl Canlı

Reputation: 434

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.

Upvotes: 0

Phong Vo
Phong Vo

Reputation: 1078

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

Upvotes: 1

Lefteris E
Lefteris E

Reputation: 2814

if (Double.TryParse(gvRow.Cells[9].Text.ToString(), out mrp))
   Console.WriteLine("Ok");
else
   Console.WriteLine("not a number");

Upvotes: 0

Blachshma
Blachshma

Reputation: 17405

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

Upvotes: 1

Habib
Habib

Reputation: 223422

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`

Upvotes: 1

Related Questions