10 个数字后 WinForms 文本框的奇怪行为

WinForms textbox strange behaivor after 10 numbers

我正在尝试使用 Visual Studio 2019 WinForms 在我的 TextBox 上放置一些控件。

这就是我的大控

int myNumber;
private void txtNumberControl_TextChanged(object sender, EventArgs e)
{
    try
    {
        if (sender != null)
        {
            myNumber = Convert.ToInt32(txtNumberControl.Text);
        }
    }
    catch (Exception)
    {
        MessageBox.Show("You can write only numbers!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
        
}

正如您从上面的代码中看到的,我试图确保用户只输入数值。奇怪的行为在写入 10 个数字后开始。因此,如果我写 12345678912 它会进入 catch 并向我显示 MessageBox 错误消息。

这是它的图片(它是意大利语,但错误是一样的,我只是翻译了它)。
myErrorMessage

但最奇怪的是,我可以写下我想要的数量 00000000000000000000000000,而且它按预期工作。

我正在寻求帮助,有人可以温柔地解释一下为什么会这样吗?

您的程序陷入困境,因为您要输入的数字现在太高,无法转换为整数。

整数的最大值为:2147483647

您已经超过了这个限制:12345678912

因此,即使您输入的数字是合法的,您的程序也无法转换并打印消息。

实际检查整个输入的字符串是否是一个数字,即使它超过了整数限制。您可以使用 .IsDigit() combined with .All() 检查是否有任何字母不是数字。

示例:

public bool CheckForNumber(string yourString) {
    // Check if all chars in this string are digits.
    if (yourString.All(char.IsDigit)) {
        return true;
    }

    return false;
}

我们现在可以将该函数与用户输入结合使用来检查它是否是有效数字。

private void txtNumberControl_TextChanged(object sender, EventArgs e) {
    // Check the text of the object that triggered this Event.
    if (!CheckForNumber((sender as Control).Text)) {
        MessageBox.Show("You can write only numbers!", "Error", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    // Try to parse the text into a long (is 0 if the input is invalid).
    if (!long.TryParse(txtNumberControl.Text, out long number)) {
        // Not validated
    }   
}