Win Form中限制TextBox只能输入数字
首先引用
using System.Text.RegularExpressions;
给TextBox添加KeyPress事件,代码如下:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((Convert.ToInt32(e.KeyChar) == 8))
{
e.Handled = false;
}
else
{
Regex numRegex = new Regex(@"^(-?[0-9]*[.]*[0-9]*)$");
Match Result = numRegex.Match(Convert.ToString(e.KeyChar));
if (Result.Success)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
}
{
if ((Convert.ToInt32(e.KeyChar) == 8))
{
e.Handled = false;
}
else
{
Regex numRegex = new Regex(@"^(-?[0-9]*[.]*[0-9]*)$");
Match Result = numRegex.Match(Convert.ToString(e.KeyChar));
if (Result.Success)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
}