文本框只接受C#中的数字

时间:2014-03-20 15:42:25

标签: c#

我正在使用法语键盘。 在顶部键盘上有键,如&,é,“,',(, - ,è,_,ç,à 使用它作为数字我必须按下shift或打开大写。

我可以在24中的文本框中放入的最大数字。

上限为capLock:我可以输入数字。 关闭capLock:我不能使用shift来输入数字。

我也可以在文本框中输入&,é,“,',(, - ,è,_,ç,à等值。

public class NumericalTextBox : TextBox
    {
        private int MaxValue;

        public NumericalTextBox()
        {
        }
        public NumericalTextBox(int max_value)
        {
            MaxValue = max_value;
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    if (e.KeyCode != Keys.Back)
                    {
                        e.SuppressKeyPress = true;
                    }
                }
            }
            if (Control.ModifierKeys == Keys.Shift)
            {
                e.SuppressKeyPress = true;
            }

        }
        protected override void OnKeyPress(KeyPressEventArgs e)
        {

            if (MaxValue >= 0 && !char.IsControl(e.KeyChar) && char.IsDigit(e.KeyChar))
            {
                try
                {
                    string s = this.Text + e.KeyChar;
                    int x = int.Parse(s);
                    if (x >= MaxValue)
                        e.Handled = true;
                }
                catch
                {
                    //e.Handled = true;
                }
            }
            base.OnKeyPress(e);
        }


    }
}

2 个答案:

答案 0 :(得分:1)

如果可以,请改用NumericUpDown - Control。它为您提供了希望的行为(过滤非数字值)。

但是,如果必须使用文本框,则Shtako-verflow的注释会指向答案。

最佳答案代码:

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

    // only allow one decimal point
    if (e.KeyChar == '.' 
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }
}

答案 1 :(得分:1)

有一种简单的方法可以实现这一目标。 您可以使用正则表达式验证器。

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ValidationExpression="^[0-9]+$"
        ErrorMessage="Only Numbers" ControlToValidate="TextBox2"></asp:RegularExpressionValidator> 

这将帮助您只接受Textbox的整数值。

相关问题