textbox只能输入数字,且长度小于指定值(c#)

        private void textBox1_TextChanged(object sender, EventArgs e)        //文本框判断
        {
            if (textBox1.TextLength > 8)
            {
                textBox1.Select(0, textBox1.Text.Length - 1);
                textBox1.Text = textBox1.SelectedText;
                textBox1.SelectAll();
                textBox1.SelectionStart = textBox1.Text.Length;
                textBox1.Focus();
            }
          
            string txt = this.textBox1.Text;
            int i = txt.Length;
            if (i < 1) return;
            for (int m = 0; m < i; m++)
            {
                string str = txt.Substring(m, 1);
                if (!char.IsNumber(Convert.ToChar(str)))
                {
                    this.textBox1.Text = this.textBox1.Text.Replace(str, ""); //将非数字文本过滤掉
                    this.textBox1.SelectionStart = this.textBox1.Text.Length;//将光标定位到最后一位
                }
            }
        }

posted on 2009-06-01 14:13  fan0136  阅读(2441)  评论(0编辑  收藏  举报