C#-WinForm控制輸入框只接受數字輸入
阿新 • • 發佈:2018-11-24
背景
給導師上一節c#編寫資料庫應用程式的課,模擬ATM自助取款機的功能寫了個winForm程式,關於金額的輸入肯定是數字,因此避免輸入格式不正確的數字帶來異常,直接在輸入時進行校驗.
封裝函式
C#輸入控制元件TextBox
,該控制元件有一個KeyPress
事件,就是鍵盤按下事件。因此可以監聽該事件。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = Common.CheckDigitFormat(this.textBox1, e); }
這裡在通用工具函式中將校驗函式進行了封住,見下面:
/// <summary> /// 判斷輸入數字是否合理 /// </summary> /// <param name="tb"></param> /// <param name="e"></param> /// <returns></returns> public static bool CheckDigitFormat(TextBox tb, KeyPressEventArgs e) { bool flag = false; if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != 46) { flag = true; } // 小數點的處理 if (e.KeyChar == 46) { if (tb.Text.Length <= 0) flag = true; //小數點不能在第一位 else { // 判斷是否是正確的小數格式 float f; float oldf; bool b1 = false, b2 = false; b1 = float.TryParse(tb.Text, out oldf); b2 = float.TryParse(tb.Text + e.KeyChar.ToString(), out f); if (b2 == false) { if (b1 == true) flag = true; else flag = false; } } } return flag; }
最後
此致,敬禮