Link to home
Start Free TrialLog in
Avatar of avi7
avi7

asked on

Cannot implicitly convert type 'string' to 'double'

Hi, I'm new to c# and am trying to convert the following code:
Thanks!

private void Sum()
    {
        double Price1 = 0;
        double Price2 = 0;

if (txtItemPrice1.Text == "")  
        {
            Price1 = 0.0;
        }
        else
        {
            Price1 = txtItemPrice1.Text; <----
        }

        if (txtItemPrice2.Text == "")
        {
            Price2 = 0.0;
        }
        else
        {    
            Price2 = txtItemPrice2.Text; <---
        }

      Error Cannot implicitly convert type 'string' to 'double'

if (IsNumeric(txtTax.Text) == false)  <----
        {
            txtTax.Text = 0.0;
        }
        else if (txtTax.Text == "")
        {
            txtTax.Text = 0.0;
        }      

TotalAmt = FormatNumber(Price1 + Price2 + txtTax.Text);      
 txtItemPriceAmt.Text = FormatNumber(TotalAmt, 2);  

Error The name 'IsNumeric' does not exist in the current context
Avatar of crysallus
crysallus
Flag of Australia image

conversions in C# are normally done using the Convert class, such as

Price2 = Convert.ToDouble(txtItemPrice2.Text);

Here's the link for all the function's available:

http://msdn.microsoft.com/en-us/library/system.convert%28v=VS.100%29.aspx

To check whether a text string can be converted to a number, use the TryParse methods of one the classes representing the base data type that your number could be in. For example, if you want to test whether the text can be converted to a double, use

if (Double.TryParse(txtTax.Text, out result) == false)
...

http://msdn.microsoft.com/en-us/library/994c0zb1.aspx
SOLUTION
Avatar of Peter Kwan
Peter Kwan
Flag of Hong Kong image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of dougaug
dougaug
Flag of Brazil image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
TryParse doesn't throw exceptions, Parse does. If you are going to use Parse as dougang suggested, you would have to surround those calls with a try-catch block. Using TryParse avoids the need for exception handling.
Avatar of avi7
avi7

ASKER

Thanks!