winForm控制输入框只接受数字输入

背景

给导师上一节c#编写数据库应用程序的课,模拟ATM自助取款机的功能写了个winForm程序,关于金额的输入肯定是数字,因此避免输入格式不正确的数字带来异常,直接在输入时进行校验.

封装函数

C#输入控件TextBox,该控件有一个KeyPress事件,就是键盘按下事件。因此可以监听该事件。

1
2
3
4
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = Common.CheckDigitFormat(this.textBox1, e);
}

这里在通用工具函数中将校验函数进行了封住,见下面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/// <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;
}

最后

此致,敬礼

~~客官随意,我只是学习怎么配置打赏而已~~