2012-04-06 21 views
-1

小文字の値を取得するテキストボックスがあります。10500.00問題は、値を入力してから小数点以下を入力すると、バックスペースまたはテキストボックスをクリアできないという問題です新しい値を入力する..それはちょうど立ち往生します..私は0.00に値を設定しようとしましたが、私は間違った場所に置いたと思います。ここに私のコードは、私がバックスペースやクリアtexboxをAN新しい値を入力することができることができるようにあなたがお勧めです変更のどのような種類小数点の入力が改善されたテキストボックス

private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @"\.\d\d"); 
      if (matchString) 
      { 
       e.Handled = true; 
      } 

      if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
      { 
       e.Handled = true; 
      } 

      // only allow one decimal point 
      if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
      { 
       e.Handled = true; 
      } 
     } 

?です。

答えて

1

あなたがバックスペース(BS)CHAR(8)のトラップをすることができますし、見つかった場合は、falseにあなたのハンドルを設定します。あなたはロジックを意味VARを作成することも

あなたのイベントハンドラが何をしているかを解釈するためのコードはもう少し直感的にする

あなたのコードは次のように見えるかもしれ...

.... 
// only allow one decimal point 
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
{ 
    e.Handled = true; 
} 

if (e.KeyChar == (char)8) 
    e.Handled = false; 

提案、あなたは実装しています。何かのように...

private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    bool ignoreKeyPress = false; 

    bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @"\.\d\d"); 

    if (e.KeyChar == '\b') // Always allow a Backspace 
     ignoreKeyPress = false; 
    else if (matchString) 
     ignoreKeyPress = true; 
    else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
     ignoreKeyPress = true; 
    else if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
     ignoreKeyPress = true;    

    e.Handled = ignoreKeyPress; 
} 
1

最も簡単な方法は、次のようになります。

if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '\b') 
{ 
    e.Handled = true; 
} 
関連する問題