winform中如何在TextBox中只能输入数字(可以带小数点)

可以采用像web表单验证的方式,利用textbox的TextChanged事件,每当textbox内容变化时,调用正则表达式的方法验证,用一个label在text后面提示输入错误,具体代码如下:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() != "")
            {
                if (!Validate(textBox1.Text.Trim(), @"^(-?d+)(.d+)?$"))
                {
                    label1.Text = "请输入数字";
                }
                else
                {
                    label1.Text = "匹配正确";
                }
            }
            else {
                label1.Text = "";
            }
        }
           /**////是否符合指定的正则表达式
        static public bool Validate(string str, string regexStr)
        {
            Regex regex = new Regex(regexStr);
            Match match = regex.Match(str);
            if (match.Success)
                return true;
            else
                return false;
        }

注意要引用命名空间:using System.Text.RegularExpressions;

原文地址:https://www.cnblogs.com/dekevin/p/4178046.html