我有一个简单的窗口应用程序,其数量就是Textbox。当我在“金额”文本框中输入“金额”时,它将将其转换为另一个名为“txtrupees”的文本框中的单词。“金额”文本框字段最大长度设置为11个位置,最后3个位置为.00。
我现在的问题是,当我输入.00的数量时,它工作得很好。但是,如果我进入11个位置,它会出现以下错误:
System.OverflowException‘发生在mscorlib.dll值中,对于in 32尝试过的代码来说,它们要么太大要么太小。
我怎样才能防止这种错误?
private void txtamount_TextChanged(object sender, EventArgs e)
{
if (txtamount.Text != string.Empty)
{
string[] amount = txtamount.Text.Split('.');
if (amount.Length == 2)
{
int rs, ps;
int.TryParse(amount[0], out rs);
int.TryParse(amount[1], out ps);
string rupees = words(rs);
string paises = words(ps);
txtrupees.Text = rupees + " rupees and " + paises + " paisa only ";
}
else if (amount.Length == 1)
{
string rupees = words(Convert.ToInt32(amount[0]));
txtrupees.Text = rupees + " rupees only";
}
}
}发布于 2017-04-26 10:07:47
这个问题来自于Convert.ToInt32(amount[0]),amount[0]几乎可以是任何东西,包括比Int.MaxValue优越或不如Int.MinValue,这会导致溢出。
使用int.TryParse(amount[0], out foo);和foo
else if (amount.Length == 1)
{
int ps;
if(int.TryParse(amount[0], out ps))
{
string rupees = words(ps);
txtrupees.Text = rupees + " rupees only";
}
else
txtrupees.Text = "Invalid number";
}如果您想处理更大的数字,可以使用Int64、Double或Decimal。
发布于 2017-04-26 10:10:57
一个有11个位置的数字比一个Int32数大。我建议你使用int64而不是int32 https://msdn.microsoft.com/en-us/library/29dh1w7z.aspx
https://stackoverflow.com/questions/43630961
复制相似问题