C# textbox接收数字、小数点

public static void Key_Press(KeyPressEventArgs e, TextBox txt)
        {
            //if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar))
            //{
            //    e.Handled = true;
            //}
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)

                e.Handled = true;


            //小数点的处理。

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

猜你喜欢

转载自www.cnblogs.com/hardenzhao/p/12436446.html