请问一下,
我想在textBox1 
里只让输入数字,
然后在textBox1里回车就运行指定程序。
这个代码该如何实现?
谢谢        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {           if ( e.KeyCode == Keys.Enter)
            {
                  // 运行
            }
         }

解决方案 »

  1.   

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
            {
     
               if ( e.KeyCode == Keys.Enter)
                {
                      TextBox sen = sender as TextBox;
                    if (System.Text.RegularExpressions.Regex.IsMatch(sen.Text.Trim(), @"^[0-9]+$"))
                    {
                       //满足
                     }
                }
             }
      

  2.   

    TextBox textBox = sender as TextBox;
                TextChange[] change = new TextChange[e.Changes.Count];
                e.Changes.CopyTo(change, 0);
                int offset = change[0].Offset;
                if (change[0].AddedLength > 0)
                {
                    double num = 0;
                    if (!Double.TryParse(textBox.Text, out num))
                    {
                        textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                        textBox.Select(offset, 0);
                    }
                }
      

  3.   

                if (e.KeyChar < '0' || e.KeyChar > '9')
                {
                    if (e.KeyChar != (char)Keys.Back)
                    {
                        e.Handled = true;
                    }            } 我找到了代码,
    但是无法在,textBox1_KeyDown
    里用,需要改。
      

  4.   

    最简单的办法是改用NumericUpDown控件。
      

  5.   

            private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (e.KeyChar !=8 &&!char.IsDigit(e.KeyChar))
                {
                    e.Handled = true;
                }
            }
      

  6.   

    我如果用KEYPRESS的话,
    KYEDOWN里的代码就不起做用了
      

  7.   


    这个textbox是输入
    产品ID值的,
    用NumericUpDown
    控件的话,
    太麻烦了。
      

  8.   

    KeyPress事件,调用
    //判斷是否為數字及'.'
            public static bool IsDigitalAndDot(char c)
            {
                char back = (char)8;
                if (char.IsDigit(c) || (bool)(c == back) || (c == '.'))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            } private void txtNumKeyPress(object sender, KeyPressEventArgs e)
            {
                if (!IsDigitalAndDot(e.KeyChar))
                {
                    e.Handled = true;
                }
            }