Reputation: 59
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
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
Reputation: 15387
Try double.tryParse
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
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
Reputation: 1078
you should try this: double mrp = gvRow.Cells[9].Text.ToString() != "" ? Convert.ToDouble(gvRow.Cells[9].Text.ToString()): 0.0;
Upvotes: 1
Reputation: 2814
if (Double.TryParse(gvRow.Cells[9].Text.ToString(), out mrp))
Console.WriteLine("Ok");
else
Console.WriteLine("not a number");
Upvotes: 0
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
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