0

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


    }
}
GameBuilder
  • 1,169
  • 4
  • 31
  • 62

2 Answers2

1

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;
    }
}
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
1

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.

Hardik Parmar
  • 1,053
  • 3
  • 15
  • 39