0

I'm using WinForms and I'm struggling trying to make all the TextBoxes from a GroupBox to accept only digits as user input. Is there a way to raise the KeyPress event for all the TextBoxes in a GroupBox? Something like this maybe:

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

I'm quite new at this, so please bear with me. Any help would be greatly appreciated.

Paul Zaval
  • 13
  • 3
  • 1
    Consider using a NumericUpDown control instead of a TextBox. It handles the numeric filtering for you automatically, and also gives the user a more intuitive interface. But if you want to use a TextBox, the clean object-oriented way to do it is to subclass the built-in TextBox control, add numeric filtering logic, and then use your subclassed control in place of the standard TextBox control everywhere you need it. – Cody Gray - on strike Apr 30 '15 at 06:09
  • what @CodyGray suggests is a nice and clean option but you could use the void that you posted here for each textbox by binding all the keypress events to that same void. – maam27 Apr 30 '15 at 06:17

1 Answers1

0

You can try this code :

    private void textBox_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;
    }
}

The source answer from here How do I make a textbox that only accepts numbers?

Community
  • 1
  • 1
Edward N
  • 997
  • 6
  • 11
  • I've already tried it. It seems, like if GroupBoxes don't have the KeyPress event at all, although the MSDN states that they do. – Paul Zaval Apr 30 '15 at 08:12
  • You can set KeyPress event of all the TextBox control to this groupBox1_KeyPress, instead of set the event of groupbox control. For example : textBox1.KeyPress += groupBox1_KeyPress, textBox2.KeyPress += groupBox1_KeyPress ... – Edward N Apr 30 '15 at 08:22
  • Thanks so much! Not only did it work, but it made me understand event handlers a bit better :) – Paul Zaval Apr 30 '15 at 17:58