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;

上一篇:create-react-app创建项目后,运行npm run eject报错解决方法


下一篇:jquery jssdk分享报错解决方法