目前很多程序員在處理TextBox中輸入數字時都採用以下代碼實現
if ((e.KeyChar != 0x08) && (e.KeyChar != 0x13) && (e.KeyChar < 0x30 || e.KeyChar > 0x39))
e.KeyChar = (char)0;
這段代碼只是簡單的過濾了非數字字符,而不能確保用戶輸入的數據是正確的,爲此我重寫了KeyPress函數。
使用該方法可以有效的確保數據的正確性,避免出現多個符號或小數點的情況。
private void tBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 0x20) e.KeyChar = (char)0; //禁止空格鍵
if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return; //處理負數
if (e.KeyChar > 0x20)
{
try
{
double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
}
catch
{
e.KeyChar = (char)0; //處理非法字符
}
}
}