最好用正则表达式好点,不会的话就用笨方法咯有直接只能输入9个字符的,在textbox中有一个maxlength的属性,你只要把它改为9就行了            if (textBox1.Text.Length >= 9)
            {
                MessageBox.Show("The length must be 9.");
                textBox1.Text = "";
                textBox1.Focus();
            }
            if (textBox1.Text.Substring(0, 1) == "0" || textBox1.Text.Substring(1, 1) == "0")//怎么对第一位和第二位单独进行限定呢?
            {
                if (textBox1.Text.Substring(0, 1) == "0")
                {
                    MessageBox.Show("The first digits cannot be zero.");
                    textBox1.Text = "";
                    textBox1.Focus();
                }
                if (textBox1.Text.Substring(1, 1) == "0")
                {
                    MessageBox.Show("The two digits cannot be zero.");
                    textBox1.Text = "";
                    textBox1.Focus();
                }
                
            }

解决方案 »

  1.   

    楼上是不是没有调试啊,textbox里一开始是没有内容的,直接用substring对其索引进行操作会报错的
      

  2.   

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {           
        if (textBox1.Text.Length >= 9 && e.KeyChar != '\b') e.Handled = true; // 够9个字符就不能输入,但可以删除
    }
      

  3.   

    sxldfang 局部问题解决,谢谢
      

  4.   


    完全满足你的要求:
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar != '\b')
        {
            string nums = ((TextBox)sender).Text + e.KeyChar;
            if (!Regex.IsMatch(nums, "^(?!00)\\d{0,9}$")) e.Handled = true;
        }
    }
      

  5.   

    sxldfang   第一位还是可以为零
    还有一点,这样子的话,我的提示框应该怎么加?
      

  6.   


                if (e.KeyCode == Keys.Enter)
                {
                    if (textBox1.Text.Length >= 9)
                    {
                        MessageBox.Show("The length must be 9.");
                        textBox1.Text = "";
                        textBox1.Focus();
                    }
                    if (textBox1.Text.Substring(0, 1) == "0" || textBox1.Text.Substring(1, 1) == "0")//怎么对第一位和第二位单独进行限定呢?
                    {
                        if (textBox1.Text.Substring(0, 1) == "0")
                        {
                            MessageBox.Show("The first digits cannot be zero.");
                            textBox1.Text = "";
                            textBox1.Focus();
                        }
                        if (textBox1.Text.Substring(1, 1) == "0")
                        {
                            MessageBox.Show("The two digits cannot be zero.");
                            textBox1.Text = "";
                            textBox1.Focus();
                        }
                    }
                }
    加个条件不就行了
      

  7.   

    superior_yong   这样子是不行的
      

  8.   

    正解,谢谢sxldfang 。
    能再帮忙写个简单的吗?  条件一:10位数字;      条件二:第一位必须为9,而且是默认自动输入进去的。所以用户只用输入后9位数字就可以了。我的做法如下:  "^\\d{0,10}$"
    在textbox的Text属性里直接先输入了数字9.  这样做的问题是用户还是可以把这个数字9删掉,再输入成别的数字。这个默认自动输入有什么办法实现吗?怎么觉得有点抽象