另一个输入字符串的格式不正确

时间:2016-06-23 07:21:41

标签: c# asp.net entity-framework linq

我在发布之前确实搜索了这个,但无法找到答案。

try
        {
            int qty, price, tot;

            qty = Convert.ToInt32(txtQty.Text);
            price = Convert.ToInt32(txtPrice.Text);

            if (DropDownList1.SelectedItem.Value == "0")
            {
                price = 10;
                tot = Convert.ToInt32(qty * price);
                txtPrice.Text = tot.ToString();
            }
            if (DropDownList1.SelectedItem.Value == "1")
            {
                price = 20;
                tot = Convert.ToInt32(qty * price);
                txtPrice.Text = tot.ToString();
            }
        }
        catch(Exception ex)
        {
            lblItemMessage.Text = ex.Message;
        }

它一直给我的信息是"输入字符串的格式不正确。"如果我之前没有使用if语句,那么它很好,但现在它只是给出了这个消息。现在它没有提供任何错误信息,但它也没有添加到数据库。

我尝试过Int32.TryParse()但它给了我同样的错误。计算出的价格假设显示在txtPrice.Text中。数量文本框采用数字文本模式。

我很感激帮助。

由于

2 个答案:

答案 0 :(得分:2)

不确定它是否会有所帮助,但由于qtyprice已经采用int格式,因此将它们再次转换为int是无用的。 所以我只想写:

  

tot = qty * price;

此外,您正在将if tot转换为字符串,因此如果要具有更好的可读性,可以将其放在第二行的末尾。像这样:

        if (DropDownList1.SelectedItem.Value == "0")
        {
            price = 10;
            tot = qty * price;
        }
        else if (DropDownList1.SelectedItem.Value == "1")
        {
            price = 20;
            tot = qty * price;
        }
        txtPrice.Text = tot.ToString();

答案 1 :(得分:1)

我对你有几点建议:

如果您使用Int32.TryParse(),它将永远不会抛出FormatException,因为如果转换失败,TryParse方法不会抛出异常。它消除了在s无效且无法成功解析的情况下使用异常处理来测试FormatException的需要。

您已将qty, price, tot声明为整数,因此您无需使用Convert.ToInt32()再次将其转换为tot

使用正确的命名约定,它将帮助您提高可读性和理解能力。

让我按如下方式重写摘录:

int itemQuantity, itemPrice, itemTotal;

if (Int32.TryParse(txtQty.Text, out itemQuantity) && Int32.TryParse(txtitemPrice.Text, out itemPrice))
{
    if (ddlOption.SelectedItem.Value == "0")
    {
       itemTotal=itemQuantity * itemPrice + 10;
       txtPrice.Text=itemTotal.ToString();
    }
    else if (ddlOption.SelectedItem.Value == "1")
    {
       itemTotal=itemQuantity * itemPrice + 20;
       txtPrice.Text=itemTotal.ToString();
    }
}