2015-05-16 64 views
0

如何讓空格鍵僅用於僅限數字的文本框?限制字符的按鍵例外

private void CLimitTxt_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (!char.IsNumber(e.KeyChar)) 
     { 
      MessageBox.Show("You can only enter numbers within this textbox", "Error"); 
      CLimitTxt.Text = ""; 
      e.Handled = true; 
     } 
    } 

我是否需要聲明一個變種正則表達式有一個例外吧?

回答

2

就這麼簡單:

private void CLimitTxt_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsNumber(e.KeyChar) && !e.KeyChar == ' ') 
    { 
     MessageBox.Show("You can only enter numbers within this textbox", "Error"); 
     CLimitTxt.Text = ""; 
     e.Handled = true; 
    } 
} 
+0

這仍然給當空格鍵被按下錯誤 – Topher

+0

好像我可以得到它使用&& char.IsControl(e.KeyChar),但它與工作空間不會讓退格被使用,那麼我認爲空格和退格都是對照? – Topher

+0

@Topher從[MSDN](https://msdn.microsoft.com/de-de/library/18zw7440%28v=vs.110%29.aspx)「_Control字符是非打印和格式化字符,如ACK ,BEL,CR,FF,LF和VT。「 嘗試if(!(char.IsNumber(e.KeyChar)|| e.KeyChar ==(char)Keys.Space))' – Simon