我正在处理数据库应用程序并使用此类来验证TextBox的KeyPress事件上的数字数字。
数字可能具有( - )具有固定小数位的负值(第三参数dPlaces),例如10000,-1000,12345.45,-12345.45
添加小数后,我无法编辑其他数字,虽然没有小数它可以正常工作。
提前致谢
public static class Util
{
public static void NumInput(object sender, KeyPressEventArgs e, int dPlaces)
{
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;
}
var a = (sender as TextBox).SelectionLength;
// only allow minus sign at the beginning
var x = (sender as TextBox).Text.IndexOf('-');
if (e.KeyChar == '-' && (sender as TextBox).Text.IndexOf('-') > 0)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= dPlaces + 1)
{
e.Handled = true;
}
}
}
}
答案 0 :(得分:0)
因为你的IF BLOCK中的逻辑操作比较长度= 3和char ='。'。
使用以下代码更改代码的最后一部分:(编辑:处理在'之前插入文字的问题。')
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
// get position of new char to be inserted
int position = textBox.SelectionStart;
if (textBox.Text.IndexOf('.') > -1 && position > textBox.Text.IndexOf('.')) // check location of new char
if(!(textBox.Text.Substring(textBox.Text.IndexOf('.')).Length <= dPlaces + 1))
{
e.Handled = true;
}
}
这将完成你的工作.. !!!
编辑:同时执行以下操作以在文本框中停止复制/过去
textbox.ShortcutsEnabled = false;