2017-05-31 99 views
-2

所以我在这里解释了这个问题: 有3个文本框,其中两个我们应该键入一些数字来添加,第三个应该显示这些总数两个数字。不能将类型'字符串'转换为'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; 
    } 
} 
} 

我无法弄清楚

+1

错误恰好告诉你问题是什么..什么你不能弄清楚..?当你调试代码时会发生什么? – MethodMan

+0

我在代码中看不到错误 - 它应该告诉你哪一行有错误? – NetMage

+1

提示 - 使用调试器检查“textBox1.Text”和“textBox2.Text”的值。迟早你应该学习如何使用调试器。那么为什么不现在开始学习? –

回答

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; 
} 
+0

不客气。请考虑将问题标记为已回答 –

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(); 
    } 
} 
相关问题