Windows Forms C# - ユーザーがテキスト ボックスから 1 つのキーを入力または削除するたびに自動的に変更されるテキスト ボックスを作成したいと考えています。コードの一部を開発しました。
//This will convert value from textbox to currency format when focus leave textbox
private void txtValormetrocubico_Leave(object sender, EventArgs e)
{
decimal cubic = Convert.ToDecimal(txtValormetrocubico.Text);
txtValormetrocubico.Text = string.Format("{0:c}", Convert.ToDecimal(cubic));
MessageBox.Show(txtValormetrocubico.Text);
}
//this only allow numbers and "." and "," on textimbox imput
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == ','
&& (sender as TextBox).Text.IndexOf(',') > -1)
{
e.Handled = true;
}
}
初めてテキスト ボックスに値を入力すると、値は のよう300
に完全に通貨形式に変換され$ 300.00
ます。しかし、このテキストボックスの値をもう一度編集してEnterキーを押すと、次の行を指す「入力文字列は正しい形式ではありませんでした」というエラーが表示されます。
decimal cubic = Convert.ToDecimal(txtValormetrocubico.Text);
問題は、値がすでに 10 進数形式になっていることが原因だと思います。フィールドをクリックしてもう一度Enterキーを押すと、値を解析できないためエラーが発生します。このエラーを回避するにはどうすればよいですか?
編集: 私の前の質問は私の最初のものでした。私は初心者で、C# の知識があまりないため、コードを投稿するのを忘れていました。もう少し勉強した後、私はそれの一部を機能させました。この小さな問題だけが残ります。賛成票を投じてください。7 票の反対票があったため、禁止され、新しい質問をすることができません。
みんなありがとう。