private void textBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if(e.KeyChar ==(char)8)
return;
    if( e.KeyChar > (char)47 && e.KeyChar < (char)58)
e.Handled = false;
    else
e.Handled = true;
}

解决方案 »

  1.   

    楼上的方法在改变输入法之后就不起作用了
    所以你还应该把输入发强制改为英文输入
    msdn的inputLanguage有详细的例子另外
    你也可以在用户输入之后用正则表达式来判断输入是否是数字
      

  2.   

    最好的方法是用正则式,不过我也不会用,编译原理里的我能看懂也会写,就是不知道.NET里的怎么用。
      

  3.   

    判断一个字符串是否全为数字
    http://community.csdn.net/Expert/topic/3284/3284647.xml?temp=.9390985
      

  4.   

    <script>
    <!--
    function txt_KeyPress(e)
             {
    e=window.event;
    var keyCode=e.keyCode;
    if(!(keyCode>=49 && keyCode<=53))
    e.keyCode=0;
    }
    -->
    </script><INPUT style="Z-INDEX: 101; LEFT: 144px; POSITION: absolute; TOP: 40px" type="text" onkeypress="txt_KeyPress()">
      

  5.   

    可以看看我的blog
    http://blog.csdn.net/hxhbluestar/archive/2004/09/08/98696.aspx
      

  6.   

    //完整的只能够从 基本数字键盘 和 小数字键盘 输入 数据的文本框
    private bool nonNumberEntered = false;
    private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
    nonNumberEntered = false;
    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9 )
    {
    // Determine whether the keystroke is a number from the keypad.
    if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
    {
    // Determine whether the keystroke is a backspace.
    if( (e.KeyCode != Keys.Back) && (e.KeyCode !=Keys.Decimal) && (e.KeyCode !=Keys.OemPeriod) )
    {
    // A non-numerical keystroke was pressed.
    // Set the flag to true and evaluate in KeyPress event.
    nonNumberEntered = true;
    }
    }
    }
    }private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if (nonNumberEntered == true)
    {
    // Stop the character from being entered into the control since it is non-numerical.
    e.Handled = true;
    }
    }如果你还要在文本框中允许输入其他 按键
    请在
    if( (e.KeyCode != Keys.Back) && (e.KeyCode !=Keys.Decimal) && (e.KeyCode !=Keys.OemPeriod) )
    中继续添加其他按键的 KeyCode 值要获取 每个键的 KeyCode 值,你可以在KeyDown()事件中
    用this.textBox1.text = e.KeyCode.ToString()获得希望问题解决!
      

  7.   

    public bool IsNumric(string text)
    {
    double d=0;
    bool isNumric=Double.TryParse(text,NumberStyles.Integer,null,out d);//判断输入是否为数字
    return isNumric;
    }
      

  8.   

    嘿﹗菜鳥不知道事件
    private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    在哪里加進去﹖如果都是自己寫進去﹐我什么才知道這個控件有沒有這個事件啊﹖
    請高手指教﹗
      

  9.   

    事件,可以在.net里让它自生成的,就是那个闪电样的图标.和控件的属性图标排在一起.
      

  10.   

    限制文本框输入的字符类型最好在KeyPress事件中处理.
      

  11.   

    各位兄弟﹐高手也進來幫我一下﹐這個小總理什么弄不清楚﹐頭痛啊
    private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    上面這行代碼什么得來已經找到了﹐但是還有呢你們上面寫e.KeyCode,當我輸入到e.時后面沒有見到有KeyCode彈出來﹐是什么回事﹖
    只有下列出來
    e.Equals;
    e.GetHashCode;
    e.GetType ;
    e.Handled ;
    e.KeyChar ;
    e.ToString ;
      

  12.   

    public static bool ValiText(string KeyIn,string ValidateString,bool Editable,string Txt,bool IsNum)
    {
    //通过 keypress 事件的 e.Handled= ValiText (e.KeyChar.ToString()  ,"0123456789.",true ,txtedit0.Text ,true);

    string Validatelist;   
    if ((Txt.IndexOf(".")>=0)&&(KeyIn==".")&&IsNum )
    return true;
    if (KeyIn == "-" && Txt.Length >0  )
    return true;
    if (Editable)
    Validatelist=ValidateString.ToUpper()+Convert.ToChar(8);
    else
    Validatelist=ValidateString.ToUpper()  ; //转成大写
    if (Validatelist.IndexOf(Convert.ToChar(KeyIn),0)<0 )
    return true;
    else
    return false;
    }
      

  13.   

    to :dzq138(钟添) ( ) 信誉:100 
    謝謝這么晚還在public static bool ValiText(string KeyIn,string ValidateString,bool Editable,string Txt,bool IsNum)
    上面這個是不是你自己定義的函數﹖
      

  14.   

    >>>>>>>各位兄弟﹐高手也進來幫我一下﹐這個小總理什么弄不清楚﹐頭痛啊
    >>>>>>>private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    >>>>>>>上面這行代碼什么得來已經找到了﹐但是還有呢
    >>>>>>>
    >>>>>>>你們上面寫e.KeyCode,當我輸入到e.時后面沒有見到有KeyCode彈出來﹐是什么回事﹖
    >>>>>>>只有下列出來
    >>>>>>>e.Equals;
    >>>>>>>e.GetHashCode;
    >>>>>>>e.GetType ;
    >>>>>>>e.Handled ;
    >>>>>>>e.KeyChar ;
    >>>>>>>e.ToString ;private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    不是这个方法
    而是
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)不是KeyDown而是KeyPress!
      

  15.   

    TO: hai2003xp(我愛豬小妹) ( ) 信誉:100 
    是的,这个函数是自己定义的.你先将其放入程序中.在你的TextBox1的KeyPress调用就可以了.如下:
    private void TextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    e.Handled= ValiText (e.KeyChar.ToString()  ,"0123456789.",true ,TextBox1.Text ,true);
    }
      

  16.   

    使用textBox.textchanged事件,每次改变以后就判断是不是数字
    bool IsNumber = false;
    int i = 0;
    try
    {
        i = Int32.Parse(textBox.text);
        IsNumber = true;
    }
    catch
    {
        IsNumber = false;
    }
      

  17.   

    我的一个实现的完整源代码。
    是我刚从库里面提取出来的,有所改动。因为原来的某些通用的调用是在另一个库中的。
    using System;
    using System.Drawing;
    using System.Windows.Forms;namespace MyLibrary.Controls
    {
    /// <summary>
    /// 一个只允许输入数字值的文本框,并且带有输入范围设置功能。
    /// </summary>
    public class NumericTextBox : System.Windows.Forms.TextBox
    {
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool MessageBeep(uint beep);

    private int minimum = -1;
    private int maximum = -1;
    private bool useRange = false;
    private string lastChar;

    public NumericTextBox()
    {
    } /// <summary>
    /// 获取或设置可以接受的数据集范围
    /// 如果设置的最大值大于等于设置的最小值,
    /// 则表示允许的值在这两个设置值之间。
    /// 如果设置的最大值小于设置的最小值,
    /// 则表示允许的值在这两个设置值之外。
    /// </summary>
    public Size SetRange
    {
    get 
    {
    if (useRange )
    return new Size(minimum, maximum);
    else 
    return new Size(-1, -1);
    }
    set 
    {
    minimum = value.Width;
    maximum = value.Height;
    }

    } /// <summary>
    /// 获取或设置是否要使用限定值的范围
    /// </summary>
    public bool UseRange
    {
    get
    {
    return this.useRange;
    }
    set
    {
    this.useRange = value;
    }
    }        protected override void OnKeyPress(KeyPressEventArgs e)
    {
    base.OnKeyPress(e);
                
    // 只能是数字,小数点符号,和后退符。
    // 可自行修改补充,以适合更广泛的要求。
    // 不建议使用正则表达式,因为根本就没必要。
    e.Handled = !(Char.IsDigit(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == 8);

    // 如果是不合要求的字符,则发出一个警告音。
    if (e.Handled)
                   MessageBeep(0x00000030);
    }
    protected override void OnValidated(EventArgs e)
    {
                base.OnValidated(e);
    if ( useRange && Text != "" ) 
    {
    int val = 0;  // 如果可以是浮点数,记得要改声明的类型哦。
    try 
    {
    // 如果想限制为整数就用 ToInt32 方法。
    // 如果可以是浮点数,可以使用 ToDecimal 或者 ToSingle 等方法。
    val = Convert.ToInt32(Text);
    }
    catch
    {
    } // 如果设置的最大值大于等于设置的最小值,
    // 则表示允许的值在这两个设置值之间。
    if (maximum >= minimum)
    {
    if ( val > maximum )
    {
    Text = maximum.ToString();
    }
    else if ( val < minimum ) 
    {
    Text = minimum.ToString();
    }
    }
    // 如果设置的最大值小于设置的最小值,
    // 则表示允许的值在这两个设置值之外。
    else
    {
    if (  val < minimum && val > maximum )
    {
    Text = maximum.ToString();
    }
    } // 如果文本长度为 1,记住它。
    // 因为用户可能会在删除了最后一个字符后,将输入焦点转移到其他控件。
    // 这么是为了能在失去焦点时保持文本框不为空。
    // 有关操作,请见 OnLostFocus。
    if ( Text.Length == 1 ) 
    {
    lastChar = Text;
    }
    }
    }

    protected override void OnLostFocus(EventArgs e)
    {
    base.OnLostFocus(e); // 当用户的输入焦点离开了此文本框时,
    // 并且当设定了数值的范围,并且文本的宽度为 0 时,
    // 将记住的最后一个字符串(必然是仅一个字符的字符串)重新填充。
    // 因为设置了范围后,就不能让文本框中为空。
    if ( Text.Length == 0 && useRange )
    {
    Text = lastChar;
    }
    }
    }
    }
      

  18.   

    重新改进了一下,现在允许输入 - 和 + 两个字符,也就是说可以处理负数了,并且将其他疏漏之处一一补齐。
    基本上可以作为一个通用控件来使用了。
    可能还有不足之处,我们一起改进吧。using System;
    using System.Drawing;
    using System.Windows.Forms;namespace MyLibrary.Controls
    {
    /// <summary>
    /// 一个只允许输入数字值的文本框,并且带有输入范围设置功能。
    /// </summary>
    public class NumericTextBox : TextBoxEx
    {
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool MessageBeep(uint beep); private int minimum = 0;
    private int maximum = 100;
    private bool useRange = false;
    private string lastChar;

    public NumericTextBox()
    {
    base.Text = "0";
    } /// <summary>
    /// 获取或设置可以接受的数据集范围
    /// 如果设置的最大值大于等于设置的最小值,
    /// 则表示允许的值在这两个设置值之间。
    /// 如果设置的最大值小于设置的最小值,
    /// 则表示允许的值在这两个设置值之外。
    /// </summary>
    public Size SetRange
    {
    get 
    {
    return new Size(minimum, maximum);
    }
    set 
    {
    if (this.SetRange == value)
    return; minimum = value.Width;
    maximum = value.Height;

    // 空文本的数值范围验证
    if (this.useRange && base.Text == "")
    {
    base.Text = GetMinimumText();
    return;
    } this.ValidateText();
    }

    }

    // 以下两个辅助方法是 VS.NET 设计器所需的。
    public bool ShouldSerializeSetRange(){ return (new Size(0, 100) != this.SetRange); }
    public void ResetSetRange() { this.maximum = 100; this.minimum = 0; }
    /// <summary>
    /// 获取或设置是否要使用限定值的范围
    /// </summary>
    [System.ComponentModel.DefaultValue(false)]
    public bool UseRange
    {
    get
    {
    return this.useRange;
    }
    set
    {
    if (this.useRange == value)
    return;
    this.useRange = value; // 空文本的数值范围验证
    if (this.useRange && base.Text == "")
    {
    base.Text = GetMinimumText();
    return;
    }
    this.ValidateText();
    }
    } /// <summary>
    /// 为了检查程序设置的文本值有效性,所以隐藏了基类的 Text 属性。
    /// </summary>
    [System.ComponentModel.DefaultValue("0")]
    public new string Text
    {
    get
    {
    return base.Text;
    }
    set
    {
    // 检查是否是一个数字
    try
    {
    Double.Parse(value);
    }
    catch
    {
    // 空文本的数值范围验证
    if (this.useRange && base.Text == "")
    {
    base.Text = GetMinimumText();
    }
    return;
    }
    base.Text = value;
    this.ValidateText();
    }
    } /// <summary>
    /// 复盖基类的 OnKeyPress 方法
    /// 用以检测按键是否符合要求。
    /// </summary>
    /// <param name="e"></param>
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
    // 回车符,检查文本数字值的有效性
    if (e.KeyChar == 13)
    {
    this.ValidateText();

    // 注意,此处要先检查后再调用基类方法
    // 因为基类方法引发的事件处理回调中需要使用到控件的值。
    // 为了回调能够得到准确的值,所以要先进行检查处理。
    base.OnKeyPress(e);

    return;
    } // 调用基类方法。先由基类来处理此次按键事件。
    base.OnKeyPress(e);
                
    // 如果基类的调用已处理了此键,直接返回吧。
    if (e.Handled)
    return; // 如果是 - 或 +,只能在第一个位置输入,且不能重复输入。
    if ( e.KeyChar == '-' || e.KeyChar == '+')
    {
    if (base.Text.StartsWith("-") || 
    base.Text.StartsWith("+") || 
    base.SelectionStart != 0) // 检测光标是否在第一个位置上
    e.Handled = true;
    }
    else if ( e.KeyChar == '.' )  // 小数点最多只能输入一个。
    {
    e.Handled = (base.Text.IndexOf('.') >= 0);
    }
    else
    {
    // 其他情况只能是数字字符和后退符。
    // 可自行修改补充,以适合更广泛的要求。
    e.Handled = !(Char.IsDigit(e.KeyChar) || e.KeyChar == 8);
    }

    // 如果是不合要求的字符,则发出一个警告音。
    if (e.Handled)
    MessageBeep(0x00000030);
    }
    /// <summary>
    /// 复盖基类的 OnValidated 方法
    /// 用以检测文本是否符合范围要求。
    /// </summary>
    /// <param name="e"></param>
    protected override void OnValidated(EventArgs e)
    {
    base.OnValidated(e);
    this.ValidateText();
    }
    /// <summary>
    /// 当非空文本时,验证文本的数值范围。
    /// </summary>
    protected virtual void ValidateText()
    {
    // 如果没有使用范围验证,直接返回
    if (this.useRange == false)
    return; // 如果文本为空、-、+,不在此作任何验证。
    if (this.IsEmpty()) 
    return; decimal val = 0;  
    bool normal = true;
    try 
    {
    val = Convert.ToDecimal(base.Text);
    }
    catch
    {
    normal = false;
    } // 如果解析正常
    if (normal)
    {
    // 如果设置的最大值大于等于设置的最小值,
    // 则表示允许的值在这两个设置值之间。
    if (maximum >= minimum)
    {
    if ( val > maximum )
    {
    base.Text = maximum.ToString();
    }
    else if ( val < minimum ) 
    {
    base.Text = minimum.ToString();
    }
    }
    // 如果设置的最大值小于设置的最小值,
    // 则表示允许的值在这两个设置值之外。
    else
    {
    if ( val < minimum && val > maximum )
    {
    base.Text = maximum.ToString();
    // 也可使用以下方法,结果相同。
    // base.Text = GetMinimumText();
    }
    }
    }
    else
    {
    // 如有异常,则使用设置的最小值。
    base.Text = GetMinimumText();
    }
    // 如果除了 - 和 + 以外的文本长度为 1,记住它。
    // 因为用户可能会在删除了最后一个字符后,将输入焦点转移到其他控件。
    // 这么是为了能在失去焦点时保持文本框不为空。
    // 有关操作,请见 OnLostFocus。
    if ( base.Text.StartsWith( "-" ) || base.Text.StartsWith( "+" ))
    {
    if ( base.Text.Length == 2)
    {
    lastChar = base.Text;
    }
    }
    else
    {
    if ( base.Text.Length == 1)
    {
    lastChar = base.Text;
    }
    }
    } protected override void OnLostFocus(EventArgs e)
    {
    base.OnLostFocus(e); // 当用户的输入焦点离开了此文本框时,
    // 并且当设定了数值的范围,并且文本的宽度为 0 时,
    // 将记住的最后字符串重新填充。
    // 因为设置了范围后,就不能让文本框中为空。
    if ( this.IsEmpty() && useRange )
    {
    if (lastChar != null)
    base.Text = lastChar;
    else
    base.Text = GetMinimumText();
    }
    }

    protected string GetMinimumText()
    {
    if (maximum >= minimum)
    {
    return minimum.ToString();
    }
    else
    {
    return maximum.ToString();
    }
    } protected bool IsEmpty()
    {
    return (base.Text == "" || base.Text == "-" || base.Text == "+");
    }
    }
    }
      

  19.   

    又有错了,不好意思。TextBoxEx 是我的另外一个扩展类,主要是外观上的改进。
    把它改为 TextBox 即可。
      

  20.   

    to :dzq138(钟添) ( ) 信誉:100 private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    e.Handled= ValiText (e.KeyChar.ToString()  ,"0123456789.",true ,textBox1.Text ,true);
    }
    我用了上面的代碼﹐有下列錯誤信息﹐這個ValiText下面有波浪線﹐是什么錯誤啊﹖什么修改回來﹖D:\Develop\WindowsApplication1\Form1.cs(339): The name 'ValiText' does not exist in the class or namespace 'WindowsApplication1.Form1'
      

  21.   

    客户端
    <SCRIPT language="JavaScript">
    function test()
    {
        if ( !((window.event.keyCode >= 48) && (window.event.keyCode <= 57)))
    {
      window.event.keyCode = 0 ;
    }

    }
    </SCRIPT>服务器端Page_Init里面me.textbox1.Attributes.Add("onkeypress", "test();")