我正在尝试开发一个代码来限制使用 C# 的 TextBox 只允许输入数字+逗号(“,”)或点(“。”)+点或逗号后仅 2 个数字所以这种方式可以查看可以输入的可能数字:
3213,04 = OK
3211,664 = Not
32.31 = OK
32.3214 = Not
334,,00 = Not
3247,.00 = Not
214.,00 = Not
32.. = Not
8465,0 = Ok
654.0 = Ok
明白我的目标了吗?我开发了下面的代码
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtValormetrocubico.TextLength >= 0 && (e.KeyChar == (char)Keys.OemPeriod || e.KeyChar == (char)Keys.Oemcomma))
{
//tests
}
else
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == ',' && (sender as TextBox).Text.IndexOf(',') > -1)
{
e.Handled = true;
}
}
}