2017-01-05 6 views
0

私はC#で新しいです。私は誰かが私を助けることを願っているStringをFloat/Intに変換するときのエラー。 C#Windows Forms

私は小さなWindowsフォームアプリケーションをプログラミングしています。 2つのテキストボックスと1つの結果ラベル。 私は数時間、textBoxのStringsから浮動小数点値を取得しようとしています。 後で、TextBox1にたとえば1.25などを書き込んで、2番目のTextBoxの値で割ります。

私は多くのコードを試しました。コードが動作している場合(赤い下線で表示されていない場合)

エラーメッセージ: "mscorlib.dllのSystem.Format.Exceptionのエラーの種類"。 "入力された文字列の形式が間違っています"。

どうすればこの問題を解決できますか?それとも、私は何が間違っているのですか?助けてください。私はNoobです。

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

    namespace WindowsFormsApplication1 
{ 


    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 

      string a = textBox1.Text; 
      string b = textBox2.Text; 

      float num = float.Parse(textBox1.Text); 

     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 

     } 
    } 
} 

`

enter image description here

+2

あなたはしていませんフォームのコンストラクタで計算を実行します。フォームのコンストラクタでは、まだユーザーがテキストを入力していません。おそらく、 'button1_Click'に' float num = float.Parse(textBox1.Text);が必要です。 – adv12

+0

これは助けになりました!どうもありがとうございました! –

答えて

2

あなたはparse関数&を使用している場合は、無効な番号が入力されて - あなたはタイプあなたの(未処理の例外の形で)エラー・メッセージが表示されます記載されている。あなたは例外処理を実装することができますいずれか

https://msdn.microsoft.com/en-us/library/2thct5cb(v=vs.110).aspx

またはTryParseメソッドを使用します:

float num; 
bool NumberOK = float.TryParse(textBox1.Text, out num); 
if (!NumberOK) 
{ 
    // report error here 
} 

https://msdn.microsoft.com/en-us/library/26sxas5t(v=vs.110).aspx

float num; 
try 
{ 
    num = float.Parse(textBox1.Text); 
} 
catch (FormatException) 
{ 
    // report format error here 
} 

あなたも範囲外に& null引数の例外をキャッチすることができます

+0

とさせていただきます。ありがとうございました! –

関連する問題