不能将'string'类型转换为'double'

时间:2017-05-31 21:23:59

标签: c#

所以我在这里解释了这个问题: 有3个文本框,其中两个我们应该输入一些要添加的数字,第三个应该显示这两个数字的总和。

错误: 不能将'string'类型转换为'double'

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Detyra2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        double nr1 = Convert.ToDouble(textBox1.Text);
        double nr2 = Convert.ToDouble(textBox2.Text);
        double nr3 = nr1 + nr2;
        string shfaq = Convert.ToString(nr3);
        textBox3.Text = shfaq;
    }
}
}

我无法弄清楚

2 个答案:

答案 0 :(得分:0)

在处理可以为null或为空的文本框时,我发现最好使用TryParse系列进行转换。

private void button1_Click(object sender, EventArgs e) {
    double nr1, nr2;

    double.TryParse(textBox1.Text, out nr1);
    double.TryParse(textBox2.Text, out nr2);
    double nr3 = nr1 + nr2;
    string shfaq = nr3.ToString();
    textBox3.Text = shfaq;
}

答案 1 :(得分:0)

您可以使用double.TryParse进行转换。 TryParse接受一个字符串输入和一个双out参数,如果它通过,它将包含转换后的值。如果转换失败,TryParse将返回false,因此您可以检查并在失败时执行其他操作:

private void button1_Click(object sender, EventArgs e)
{
    double nr1;
    double nr2;

    if (!double.TryParse(textBox1.Text, out nr1))
    {
        MessageBox.Show("Please enter a valid number in textBox1");
        textBox1.Select();
        textBox1.SelectionStart = 0;
        textBox1.SelectionLength = textBox1.TextLength;
    }
    else if (!double.TryParse(textBox2.Text, out nr2))
    {
        MessageBox.Show("Please enter a valid number in textBox2");
        textBox2.Select();
        textBox2.SelectionStart = 0;
        textBox2.SelectionLength = textBox2.TextLength;
    }
    else
    {
        double nr3 = nr1 + nr2;
        textBox3.Text = nr3.ToString();
    }
}
相关问题