我有一个简单的Windows应用程序,文本框就在那里.当我在金额文本框中输入金额时,它会将其转换为另一个名为的文本框中的单词txtrupees.金额文本框字段最大长度设置为最后3个位置.00的11个位置.
我现在的问题是,当我输入金额为.00时工作正常.但如果我进入11个位置,它将给出以下错误:
mscorlib.dll中发生System.OverflowException对于Int32.tried下面的代码,值太大或太小.
我怎样才能防止出现这种错误?
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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题来自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";
}
Run Code Online (Sandbox Code Playgroud)
如果你想处理更大的数字,你可以使用Int64,Double或Decimal
| 归档时间: |
|
| 查看次数: |
668 次 |
| 最近记录: |