2017-05-31 3 views
-2

ここで私は問題を説明しています: 2つのテキストボックスに2つの数字を入力して追加し、 2つの数字。暗黙のうちにタイプ '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; 
    } 
} 
} 

は、私は

+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パラメータを受け取ります。このパラメータは、渡された場合に変換された値を含みます。変換が失敗した場合はfalse TryParse戻り、あなたがそれをチェックして、失敗した場合に別の何かを行うことができますので、:

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(); 
    } 
} 
関連する問題