首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C# 输入框最后一位数目字无法删除

2013-12-05 
C# 输入框最后一位数字无法删除t4.KeyPress + new System.Windows.Forms.KeyPressEventHandler(text_KeyP

C# 输入框最后一位数字无法删除
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);
在网上找到这两段代码,贴上去了,才发现输入数字后删除,个位总删不掉

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;
            }
        }

[解决办法]
你可以控制输入框只能输入除数字意外的其他任意字符

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = false;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
                e.Handled = true;
        }

热点排行