如果是Win Form可以在按键事件里处理,如果是Web Form可以用数据校验控件或客户端脚本来处理。

解决方案 »

  1.   

    Web Form中,用RegularExpressionValidator控件来验证:
    ControlToValidate属性为你要验证的TextBox的ID;
    ValidationExpress为"\d*"就可以了。
      

  2.   

    如果是WinForm的textBox,那么可以这样:
    在KeyPress事件中写如下代码:
            if  (!(Char.IsNumber(e.KeyChar)  ||  e.KeyChar  ==  '\b'))  
            {
              e.Handled  =  true;
            }
      

  3.   

    如果是WebForm的textBox,那么可以这样
    <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="年输入有误,请重输!" ControlToValidate="textBox控件ID" ValidationExpression="[0-9]{4}"></asp:RegularExpressionValidator></P>
      

  4.   

    public  class  form2:System.Windows.Forms.Form
        {
          public  form2()
          {
            this.Text  =  "form2";
          }
        }
      

  5.   

    上面的发错了
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if(e.KeyChar>56)
    notGet();
    else
    getIt();

    } private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    { } private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
    {
    if(e.KeyValue>104)
    notGet();
    else
    getIt(); } public void notGet()
    {
    textBox1.Text=textBox2.Text;
    } public void getIt()
    {
    textBox2.Text=textBox1.Text;
    }
      

  6.   

    我的例子
    private void textBoxTotalPrice_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    char theChar = e.KeyChar;
    string str = "1234567890"+(char)8;
      if ( str.IndexOf(theChar.ToString()) < 0 )
      {
        e.Handled = true;
        throw new Exception("不正确的输入,请只输入0-9");
      } 
    }