C# TextBox中只允许输入数字的方法

来源:互联网 发布:记录轨迹软件 编辑:程序博客网 时间:2024/05/16 18:35
1.在Winform(C#)中要实现限制Textbox只能输入数字,一般的做法就是在按键事件中处理,
 判断keychar的值。限制只能输入数字,小数点,Backspace,del这几个键。数字0~9所
 对应的keychar为48~57,小数点是46,Backspace是8,小数点是46。 


2.输入小数点。输入的小数要符合数字的格式,类似9.9.9这样的是不能够输入的。做法就是用float.TryParse来转换Textbox中之前和之后的值,然后比较两者的转换结果。


在如下代码中,实现了控件textBox1中输入数字。
在控件textBox1中的KeyPress时间中输入如下代码


private void txtTaxrate_KeyPress(object sender, KeyPressEventArgs e)
        {
             //判断按键是不是要输入的类型。
                 if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar !=46 )
                    e.Handled = true;


                 //小数点的处理。
                 if ((int)e.KeyChar == 46)                           //小数点
                 {
                     if (txtTaxrate.Text.Length <= 0)
                         e.Handled = true;   //小数点不能在第一位
                     else
                     {
                         float f;
                         float oldf;
                         bool b1 = false, b2 = false;
                         b1 = float.TryParse(txtTaxrate.Text, out oldf);
                         b2 = float.TryParse(txtTaxrate.Text + e.KeyChar.ToString(), out f);
                         if (b2 == false)
                         {
                             if (b1 == true)
                                 e.Handled = true;
                             else
                                 e.Handled = false;
                         }
                     }
                 }
        }
0 0