2017-06-11 2 views
0

リストボックスからコンボボックスにアイテムを追加した後、合計アイテムの価格を計算しようとしています。リストボックスには、商品のタイプと価格の両方があります。コンボボックスに各項目を追加(addButtonをクリック)すると合計金額が増加することがわかります。しかし、私が見ているのは、コンボボックスにアイテムが追加されているのですが、価格の合計ではなく個々のアイテムの価格だけが表示されます。ここに私のコードのサンプルがあります。ループの合計アイテムを使用する方法

private void addButton_Click(object sender, EventArgs e) 
{ 
    decimal price;  // variables to holds the price 

    decimal total = 0; // variables to hold the total 
    int counter; 

    for (counter=0; counter <= 5; counter++) 
    {  
     price = decimal.Parse(priceLabel2.Text); 
     // add items price 
     total += price; 

     // display the total amount 
     costLabel.Text = total.ToString("c"); 
    } 

任意の助けをいただければ幸い、

+0

4つのアイテムを追加すると、最後に表示された合計(現在)が表示されますか? – mjwills

+0

はい、最後のものだけが表示されます。 –

+1

あなたが与えた説明に関連するコードを投稿すると、助けがはるかに簡単になります。リストボックスとコンボボックスについて説明し、次にいくつかのラベルを扱うコードを投稿します。また、くぼみを固定してください。 –

答えて

4

変更:

private void addButton_Click(object sender, EventArgs e) 
    { 
     decimal price;  // variables to holds the price 

     decimal total = 0; // variables to hold the total 
     int counter; 

      for (counter=0; counter <= 5; counter++) 
      { 

      price = decimal.Parse(priceLabel2.Text); 
      // add items price 
      total += price; 

      // display the total amount 
      costLabel.Text = total.ToString("c"); 
      } 

へ:

decimal total = 0; // variables to hold the total 

    private void addButton_Click(object sender, EventArgs e) 
    { 
     decimal price; // variables to holds the price 

     int counter; 

     for (counter = 0; counter <= 5; counter++) 
     { 
      price = decimal.Parse(priceLabel2.Text); 
      // add items price 
      total += price; 

      // display the total amount 
      costLabel.Text = total.ToString("c"); 
     } 
    } 

ここで重要な変更は、全変数機能を動かしています。これは、値がクリック間で維持されることを意味します。関数の中に置くと、クリックごとに0にリセットされます(これはあなたが望むものではありません)。

+5

に投票しました。 (1)インデントを修正する、(2)関数の外で変数totalを動かすことが問題を解決する理由を説明することができます。私はあなたがdownvotes持っていると思う。また別の方法があります:関数の始めに 'costLabel'から現在の合計値を取得し、外部変数を持たないようにします。 – Rafalon

+0

あなたは何も説明しませんでした。あなたはちょうど正しいバージョンを貼り付けました... – FCin

+0

偉大なフィードバック - ありがとう@ラファロンとFCin。私はあなたのコメントに基づいていくつかの変更を加えました。再度、感謝します! – mjwills

関連する問題