GroupBox 中的 C# 纯数字文本框。

C# Digit-only TextBoxes in a GroupBox.

我正在使用 WinForms,我正在努力尝试使 GroupBox 中的所有 TextBoxes 只接受数字作为用户输入。有没有办法为 GroupBox 中的所有 TextBoxes 引发 KeyPress 事件?可能是这样的:

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

我对此很陌生,所以请多多包涵。任何帮助将不胜感激。

你可以试试这个代码:

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

来源答案来自这里How do I make a textbox that only accepts numbers?