在文本框中,数值过大或过小导致 Int32 类型溢出。

3

在数量文本框中输入超过11个数字时,我会遇到错误:int b = Convert.ToInt32(qty.Text);

if (Item_Name.Text == dr["Item_Name"].ToString() && Item_Code.Text == dr["Item_Code"].ToString())
                {
                    int a = Convert.ToInt32(dr["Selling_Price"].ToString());
                    if (qty.Text == "")
                    {
                        Selling_Price.Text = "";
                    }
                    else
                    {
                        int b = Convert.ToInt32(qty.Text); //Error On This Line
                        int c = a * b;
                        Selling_Price.Text = c.ToString();
                    }
                }

https://msdn.microsoft.com/en-us/library/system.int32.maxvalue(v=vs.110).aspx - Ofir Winegarten
@Grant Even,10个数字都可能存在这个问题。 - user123456
1个回答

6
您之所以会遇到这个异常,是因为一个整数无法存储如此大的数字。请参考Int32.MaxValue Field了解更多信息。
如果您使用long类型,则应该可以解决问题。当您处理代表货币的数字时,建议考虑使用decimal类型。
if (Item_Name.Text == dr["Item_Name"].ToString() && Item_Code.Text == dr["Item_Code"].ToString())
{
    int price = Convert.ToInt32(dr["Selling_Price"].ToString());
    if (qty.Text == "")
    {
        Selling_Price.Text = "";
    }
    else
    {
        long quantity = Convert.ToInt64(qty.Text);
        long total = price * quantity;
        Selling_Price.Text = total.ToString();
    }
}

如果您也能回答我这个问题,我将非常感激您: - Usama
我正在使用C# Windows Form。我有一个数量文本框,如果我为所选项目输入的数量超过了现有库存,那么我该如何显示消息框,并且我希望文本框的最大长度应等于可用库存。 - Usama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接