背景
給導師上一節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;
}
最后
此致,敬禮