简体   繁体   中英

Text box to accept only number in C#

i am using a French keyboard. On top keyboard there are keys like &,é,",',(,-,è,_,ç,à to use it as a number i have to press shift or turn the capslock on.

maximum number that i can put in text box in 24.

with capLock on : i can put numbers. with capLock off : i cannot put numbers using shift.

also i can put values like &,é,",',(,-,è,_,ç,à in the text box.

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);
        }


    }
}

If you can, use the NumericUpDown -Control instead. It provides you the wished behaviour (filtering non-numeric values).

However, if you must use a textbox, the comment of Shtako-verflow points to the answer.

The top answer's code:

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;
    }
}

There is one simple method to achieve this. You can use regular expression validator for this.

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

This will help you to only accept integer values for Textbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM