不能隐式转换类型'字符串'到'加倍

时间:2014-12-01 00:38:50

标签: c#

大家好我试图使用设置文本框只接受双数据类型作为产品价格接受的输入类型,但我得到以下错误:cannot implicitly convert type 'string' to 'double'。有人能指出我正确的方向吗?

((Employee)o).ProdPrice = this.textProdName.Text;

我在this.textProdName.Text下得到了错误。

3 个答案:

答案 0 :(得分:1)

  

我正在尝试使用设置文本框仅接受双数据类型作为产品价格接受的输入类型

假设您已经验证文本框只接受双值,则需要将this.textProdName.Text转换为双倍

((Employee)o).ProdPrice = Convert.ToDouble(this.textProdName.Text);

但是,如果文本框无法转换为double,请使用Double.TryParse,如下所示

Double prodPrice = 0;

if (Double.TryParse(this.textProdName.Text, out prodPrice))
{
    ((Employee)o).ProdPrice = prodPrice;
}
else
{
    // do something when textProdName.Text can't be converted to double
}

答案 1 :(得分:1)

尝试Convert.toDoubleDouble.Parse

这样:((Employee)o).ProdPrice = Convert.ToDouble(this.textProdName.Text);((Employee)o).ProdPrice = Double.Parse(this.textProdName.Text);

答案 2 :(得分:1)

我更喜欢TryParse,因为如果不能解析字符串,我可以决定返回什么值,在下面的示例中我使用了Doube.NaN。

Double val;

((Employee)o).ProdPrice = Double.TryParse(this.textProdName.Text, out val)?val:Double.NaN;
相关问题