C# 设置文本框只能输入数字和小数点

private void input_weight_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 (input_weight.Text.Length <= 0)

                    e.Handled = true;   //小数点不能在第一位

                else

                {

                    float f;

                    float oldf;

                    bool b1 = false, b2 = false;

                    b1 = float.TryParse(input_weight.Text, out oldf);

                    b2 = float.TryParse(input_weight.Text + e.KeyChar.ToString(), out f);

                    if (b2 == false)

                    {

                        if (b1 == true)

                            e.Handled = true;

                        else

                            e.Handled = false;

                    }

                }
            }

        }

你可能感兴趣的:(C#基础,c#,开发语言)