C#input输入框最后一位数字无法删除
t4.KeyPress += new System.Windows.Forms.KeyPressEventHandler(text_KeyPress); t5.KeyPress += new System.Windows.Forms.KeyPressEventHandler(text_KeyPress); t4.TextChanged += new EventHandler(text_TextChanged); t5.TextChanged += new EventHandler(text_TextChanged); 在网上找到这两段代码,贴上去了,才发现输入数字后删除,个位总删不掉
C# code?123456789101112131415 private void text_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8 || e.KeyChar == '.'); if (!e.Handled) (sender as TextBox).Tag = (sender as TextBox).Text;//记录最后一次正确输入 } private void text_TextChanged(object sender, EventArgs e) { if (!System.Text.RegularExpressions.Regex.IsMatch((sender as TextBox).Text, @"^(?!0\d)\d+(\.\d*)?$")) { int index = (sender as TextBox).SelectionStart; (sender as TextBox).Text = (sender as TextBox).Tag as string; (sender as TextBox).SelectionStart = index; } } 不知道是什么原因,是因为@"^(?!0\d)\d+(\.\d*)?$"吗 请教大神们 应该怎么修改啊?
因为空字符串不匹配@"^(?!0\d)\d+(\.\d*)?$"),这样文件就是用tag中的值(个位数)。 加个判断,如果为空字符串,不判断正则 private void text_TextChanged(object sender, EventArgs e) { if ((sender as TextBox).Text == "") { return; } if (!System.Text.RegularExpressions.Regex.IsMatch((sender as TextBox).Text, @"^(?!0\d)\d+(\.\d*)?$")) { int index = (sender as TextBox).SelectionStart; (sender as TextBox).Text = (sender as TextBox).Tag as string; (sender as TextBox).SelectionStart = index; } }
|