2013-10-24 63 views
0

允許退格鍵,我驗證用戶輸入只接受數字中的WinForms輸入字段

private void txtEdition_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if ((int)e.KeyChar < 48 || e.KeyChar > 57) 
     e.Handled = true; 
} 

但在此輸入字段,這也禁用退格。如何允許退格?

回答

0

你可以使用

if (!Char.IsNumber(e.KeyChar) && 
    !Char.IsControl(e.KeyChar)) 
{ 
    e.Handled = true; 
} 

Char.IsNumber表示Unicode字符是否被歸類爲若干
Char.IsControl指示指定的Unicode字符是否被歸類爲控制字符。

但是,這不會阻止複製/粘貼操作,因此你還需要使用某種類型的TryParse的驗證輸入,當你需要在這個文本框中鍵入的數據

+0

這也可能是值得設置文本菜單進行TextBox將成爲一個新的ContextMenu,這將阻止用戶右鍵單擊並粘貼非數字字符。 – Satal