Search code examples
c#eventstextboxgroupbox

C# Digit-only TextBoxes in a GroupBox.


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.


Solution

  • 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?