views:

84

answers:

2

I am attempting to cast a string gotten from a local database into decimal, but resulted in a "Cannot implicitly convert Type 'GlobalCurrencyConverter.CurrencyRateDataSet.rateDataTable' to decimal".

Below is my code,

protected decimal calRate_Click(object sender, EventArgs e)
{
    CurrencyRateDataSetTableAdapters.rateTableAdapter rateTable;
    decimal exRate = (decimal)rateTable.GetDataBySourceTargetCurrency(objDropDownSourceCUR.SelectedValue, objDropDownTargetCUR.SelectedValue);
    decimal exAmt = 0;
    exAmt = (decimal)Convert.ToDecimal(objTextBoxSourceAmt.Text);
}

Update:

rateTable.getDataBySourceTargetCurrency is a method created in Visual Studio Designer. It takes in 2 parameters and search through the local database, returning a single row (and single column) of value.

A: 

If "rateTable.GetDataBySourceTargetCurrency(objDropDownSourceCUR.SelectedValue, objDropDownTargetCUR.SelectedValue)" is in fact a string (from your title), try Decimal.TryParse():

//Just noticed questions above... if rateTable.GetDataBy... does not return a string, you must create a string from whatever object it does return, then use TryParse()

Decimal exRate;
String exRateString = rateTable.GetDataBySourceTargetCurrency(objDropDownSourceCUR.SelectedValue, objDropDownTargetCUR.SelectedValue);

bool convertSuccessful = Decimal.TryParse(exRateString, out exRate);
if (convertSuccessful == true)
{
     // do some stuff here
}
else
{
     // report error
}
cdkMoose
A: 

Try this:

public static class StringUtils
{
    public static string ToCurrency(decimal value)
    {
        return value.ToString("C");
    }

    public static decimal FromCurrency(string value)
    {
        return decimal.Parse(value, NumberStyles.Currency);
    }

    public static decimal? FromCurrency(string value, decimal? defaultValue)
    {
        decimal num;
        if(decimal.TryParse(value, NumberStyles.Currency, null, out num))
            return num;
        return defaultValue;
    }
}

From which you can do this:

decimal exAmt = StringUtils.FromCurrency(objTextBoxSourceAmt.Text,0);
Tawani