-4

数量と価格のテキストボックスの値を乗算してから、追加ボタンが押されるたびに更新される合計テキストボックスにそれを渡そうとしています。以下は、私がこれまでに試したことです。

合計テキスト ボックスに製品を表示して累積するにはどうすればよいですか? たとえば、数量 4 で価格 4 の場合、16 と表示されます。数量 2 と価格 2 を入力すると、20 と表示されます。

private void add_btn_Click(object sender, EventArgs e)
    {
        try
        {
            if (customer_textBox.Text == "")
            {
                MessageBox.Show(
                    "Please enter valid Customer");
            }
            if (quantity_textBox.Text == "")
            {
                MessageBox.Show(
                    "Please enter valid Quantity");
            }
            if (price_per_item_textBox.Text == "")
            {
                MessageBox.Show(
                    "Please enter valid Price");
            }
            else
            {
                decimal total = Decimal.Parse(total_textBox.Text);
                total = int.Parse(quantity_textBox.Text) * int.Parse(price_per_item_textBox.Text);
                total += total;
                total_textBox.Text = total.ToString();
            }
            quantity_textBox.Clear();
            customer_textBox.Clear();
            price_per_item_textBox.Clear();
            item_textBox.Clear();
        }
        catch (FormatException)
        {

        }
        total_textBox.Focus();


    }
4

1 に答える 1

3

これを変える

decimal total = Decimal.Parse(total_textBox.Text);
total = int.Parse(quantity_textBox.Text) * int.Parse(price_per_item_textBox.Text);
total += total;
total_textBox.Text = total.ToString();

これに

total = currentTotal + (decimal.Parse(quantity_textBox.Text) * decimal.Parse(price_per_item_textBox.Text));
total_textBox.Text = total.ToString("C");

クラスレベルの変数を作成しますprivate decimal currentTotal;

4 行目のテキスト ボックスの値を再割り当てするだけなので、1 行目は必要ありません。アイテムあたりの価格はdecimal値 (例: $1.99) であると想定しています。として解析するとint、精度が失われます (例: $1.99 は 1 になります)。と を掛けると も返さintれます。$1.99 * 2 は 1 * 2 になり、$3.98 ではなく単純に 2 になります。intint

于 2013-04-28T23:16:07.130 に答える