C# 将字符串转换为十进制
我试图将从本地数据库获取的字符串转换为十进制,但导致“无法将类型'GlobalCurrencyConverter.CurrencyRateDataSet.rateDataTable'隐式转换为十进制” 下面是我的代码C# 将字符串转换为十进制,c#,casting,decimal,C#,Casting,Decimal,我试图将从本地数据库获取的字符串转换为十进制,但导致“无法将类型'GlobalCurrencyConverter.CurrencyRateDataSet.rateDataTable'隐式转换为十进制” 下面是我的代码 protected decimal calRate_Click(object sender, EventArgs e) { CurrencyRateDataSetTableAdapters.rateTableAdapter rateTable; decimal ex
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);
}
更新:
rateTable.GetDatabaseSourceTargetCurrency是在Visual Studio Designer中创建的方法。它接受2个参数并搜索本地数据库,返回一行(和一列)值。如果“rateTable.GetDatabaseSourceTargetCurrency(objDropDownSourceCUR.SelectedValue,objDropDownTargetCUR.SelectedValue)”实际上是一个字符串(来自标题),请尝试Decimal.TryParse():
//刚刚注意到上面的问题。。。如果rateTable.GetDataBy。。。如果不返回字符串,则必须从它返回的任何对象创建字符串,然后使用TryParse()
试试这个:
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;
}
}
您可以从中执行以下操作:
decimal exAmt = StringUtils.FromCurrency(objTextBoxSourceAmt.Text,0);
你能为这个方法编写代码吗rateTable.GetDatabaseSourceTargetCurrency()rateTable.GetDatabaseSourceTargetCurrency返回什么?它可能返回一个数据表,然后只返回一列和一行,尝试访问其中的值,更像(十进制)rateTable.GetDatabaseSourceTargetCurrency(objdropdownstourcecur.SelectedValue,objdropdownstargetcur.SelectedValue)[0][0];
decimal exAmt = StringUtils.FromCurrency(objTextBoxSourceAmt.Text,0);