2017-02-19 20 views
-2

こんにちは、レストラン管理システムとIm tyringで作業して、合計ボタンをクリックしたときのアイテムのコストを計算してください。 C#のに非常に精通していないイムしかし、私は、エラーメッセージが出続ける:型「にSystem.FormatException」の未処理の例外をエラーメッセージ:mscorlib.dllで 'System.FormatException'の未処理の例外が発生しました。#

コードがmscorlib.dllで発生した

private void btntotal_Click(object sender, EventArgs e) 
    { 

     double[] itemtotal = new double[12]; 
     itemtotal[0] = Convert.ToDouble(txtspringroll.Text) * Price_springroll; 
     itemtotal[1] = Convert.ToDouble(txtsamosa.Text) * Price_samosa; 
     itemtotal[2] = Convert.ToDouble(txtsalmon.Text) * Price_salmon; 
     itemtotal[3] = Convert.ToDouble(txttarator.Text) * Price_tarator; 
     itemtotal[4] = Convert.ToDouble(txtshkembe.Text) * Price_shkembe; 
     itemtotal[5] = Convert.ToDouble(txtguveche.Text) * Price_guveche; 
     itemtotal[6] = Convert.ToDouble(txtbanista.Text) * Price_banista; 
     itemtotal[7] = Convert.ToDouble(txtgarash.Text) * Price_garash; 
     itemtotal[8] = Convert.ToDouble(txtbaklava.Text) * Price_baklava; 
     itemtotal[9] = Convert.ToDouble(txtwater.Text) * Price_water; 
     itemtotal[10] = Convert.ToDouble(txtcoke.Text) * Price_coke; 
     itemtotal[11] = Convert.ToDouble(txtapple.Text) *Price_apple; 


     totalcost = itemtotal[0] + itemtotal[1] + itemtotal[2] + itemtotal[3] + itemtotal[4] + itemtotal[5] + itemtotal[6] + itemtotal[7] + itemtotal[8] + itemtotal[9] + itemtotal[10] + itemtotal[11]; 
     txtTotal.Text = Convert.ToString(totalcost); 


    } 
+0

テキストボックスのようなものは、2倍の値に変換可能なテキストを持っていないようです。数値の入力にNumericUpDownを使用することをお勧めします。 –

+0

すべてのテキストボックスに有効なdouble値があることを確認しましたか? –

+0

あなたの問題は上記で説明しましたが、_itemtotal []。Sum()_メソッドを使用できることを知っておく必要があります。お金の値を処理する場合、使用する正しいデータ型は_decimal_ – Steve

答えて

0

あなたはとき変換例外を取得しています.ToDoubleは有効な番号ではない文字列を受け取ります。 (空の文字列であっても、このメソッドでは無効です)。
入力が有効な数値でない場合に例外を発生させることなく、テキスト入力を数値に変換するには、データ型に適したTryParseメソッドを使用する必要があります。

しかし、お金の値を扱うときは、浮動小数点型に起因する丸め誤差を避けるために10進データ型を使用する必要があります。

decimal[] itemtotal = new decimal[12]; 

// If the conversion succeed the itemtotal[0] contains the converted value 
// otherwise it contains the default value for a decimal (0) 
decimal.TryParse(txtspringroll.Text, out itemtotal[0]); 
itemtotal[0] *= Price_springroll; 

// and so on for the other elements of the array 

txtTotal.Text = itemtotal.Sum().ToString(); 
+0

です。 – user999991

関連する問題