消費税計算機の機能Up
税抜き価格を入力するたびに税込価格が更新できるようにしてみましょう
目次
実行結果
次のようにすることを目標に見ていきましょう
対応
入力された文字列、また計算結果を右寄せにしましょう
入力されるたびに計算がなされる
税込価格が変更できないようにする
税込価格が通貨表示なるようにする
書式設定を「C」として、通貨表示するようにします
texPriceBox.Text = $"{(int)(price * 1.1):C}";
全体のコード
using System;
using System.Windows.Forms;
namespace TaxCalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calcButton_Click(object sender, EventArgs e)
{
int price;
bool success = int.TryParse(priceBox.Text, out price);
if (success)
{
texPriceBox.Text = $"{(int)(price * 1.1):C}";
}
}
}
}
おまけ
途中に数値以外が入力された時にも対応する
priceBoxのプロパティの更新

コードの更新
using System;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace TaxCalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calcButton_Click(object sender, EventArgs e)
{
CalcTax();
}
private void CalcTax()
{
int price;
bool success = int.TryParse(priceBox.Text, out price);
if (success)
{
texPriceBox.Text = $"{(int)(price * 1.1):C}";
}
}
private void priceBox_KeyUp(object sender, KeyEventArgs e)
{
CalcTax();
}
private void priceBox_KeyPress(object sender, KeyPressEventArgs e)
{
// 数字以外のキーを無視する
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("数値を入力してね");
}
}
}
}
calcButton_Click
メソッドとpriceBox_KeyUp
メソッドによって、「計算ボタン」がクリックされたり、priceBox
のキーが押されたりした時に税金を計算することができます。また、priceBox_KeyPress
メソッドにより、数字以外のキーが押された場合には、そのキーを無視して警告メッセージを表示することができます。
キーイベントハンドラの説明
private void priceBox_KeyPress(object sender, KeyPressEventArgs e)
{
// 数字以外のキーを無視する
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("数値を入力してね");
}
}
このコードは、テキストボックス内でキーが押されたときに発生するイベントハンドラーです。このハンドラーは、キーが数字でない場合(例えばアルファベットや特殊文字)、キーイベントを無視します。代わりに、「数値を入力してね」というメッセージボックスを表示します。
priceBoxのプロパティの更新

ディスカッション
コメント一覧
まだ、コメントがありません