如何解决WinForms文本框后10个数字奇怪behaivor
我正在尝试使用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()
和.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
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。