对于文本框中的Int32,值太大或太小

时间:2017-10-29 12:05:54

标签: c#

如果我在数量文本框中键入超过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();
                    }
                }

1 个答案:

答案 0 :(得分:3)

您获得该异常是因为integer cannot store a number that large

  

Int32.MaxValue字段:此常量的值为2147483647

切换到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();
    }
}