2012-04-06 69 views
-1

我有一個文本框獲取十進制值,說10500.00問題是,我有它的方式,當你輸入一個值,然後輸入小數,它不會讓你退格或清除文本框輸入一個新的值..它只是卡住..我試圖將值設回0.00,但我認爲我把它放在錯誤的地方,因爲它不會改變它。這裏是我的代碼帶有十進制輸入改進的文本框

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; 
      } 
     } 

你的建議是什麼類型的變化,這樣我或許可以退格或清除texbox一個輸入一個新值?

回答

1

您可以陷阱退格(BS)CHAR(8),如有發現,你的手柄設置爲false。

您的代碼可能會是這樣......

.... 
// 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; 

有人建議讓你的代碼更直觀一點來解釋你的事件處理程序是幹什麼的,你可能希望創建意味着邏輯VAR你正在執行。類似...

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; 
} 
相關問題