Search code examples
c#textboxnumberslimiting

Restricting Input to Numbers Only In Textbox? (c#)


Please excuse me for asking this, I have looked at various different questions relating to this and I still can not get it to implement.

Using the answers I have looked at, I have gathered this, and applied this coding to my text box.

private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            e.Handled = true;
    }

Now, when I proceed to run the program, I am still able to enter letters into it. I do not know what to do next, so any solution would be great. thanks.


Solution

  • Okay this is what i made just now, it works 100% just tested it.Note that my textBox is named serialTxtBox, you can change it to yours.

    void serialTxtBox_TextChanged(object sender, EventArgs e)
            {
                bool enteredLetter = false;
                Queue<char> text = new Queue<char>();
                foreach (var ch in this.serialTxtBox.Text)
                {
                    if (char.IsDigit(ch))
                    {
                        text.Enqueue(ch);
                    }
                    else
                    {
                        enteredLetter = true;
                    }
                }
    
                if (enteredLetter)
                {
                    StringBuilder sb = new StringBuilder();
                    while (text.Count > 0)
                    {
                        sb.Append(text.Dequeue());
                    }                
    
                    this.serialTxtBox.Text = sb.ToString();
                    this.serialTxtBox.SelectionStart = this.serialTxtBox.Text.Length;
                }
            }
    

    EDIT: Definitely you are doing something wrong. In your form constructor which is named like your form. In my case SerialGenerator, you need to initialize the event. In my case :

    public SerialGenerator()
            {
                InitializeComponent();
                this.serialTxtBox.TextChanged += serialTxtBox_TextChanged;
            }
    

    this will fire the method everytime someone enters something in your textBox. Make sure you rename it to your textbox's name