输入字符串格式不正确

时间:2013-08-27 01:56:50

标签: c#

        if (Session["totalCost"] != null)
        {
             if (Session["totalCost"] != "confirm")
             {
                totRevenueLabel.Text = totalRevenueInteger.ToString();
                totalRevenueInteger += int.Parse(Session["totalCost"].ToString());
             }

然而,当我执行程序时,它表示输入字符串没有以正确的格式放置

请帮忙!

3 个答案:

答案 0 :(得分:2)

你正在解析

int.Parse(Session["totalCost"].ToString());

因此假设Session["totalCost"]具有字符串格式的数值。但是你早些时候在做:

if (Session["totalCost"] != "confirm")

表示Session["totalCost"]包含字符串格式的字母。两种说法都是相反的。我希望你现在能找到你的问题。

答案 1 :(得分:1)

错误意味着您尝试解析整数的字符串实际上不包含有效整数。

int i;
if(int.TryParse(Session["totalCost"].ToString(), out i)
{
   totalRevenueInteger = i;
}

答案 2 :(得分:1)

如果Session["totalCost"].ToString())为空或空int.parse将抛出input string was not put correct format

尝试添加错误处理或使用int.TryParse并设置默认值

示例:

         if (Session["totalCost"] != "confirm")
         {
            totRevenueLabel.Text = totalRevenueInteger.ToString();

            int value = 0;
            int.TryParse(Session["totalCost"].ToString(), out value);

            totalRevenueInteger += value;
         }

         if (Session["totalCost"] != "confirm")
         {
            totRevenueLabel.Text = totalRevenueInteger.ToString();

            string value = Session["totalCost"].ToString();

            totalRevenueInteger += !string.IsNullOrEmpty(value) ? int.TryParse(value) : 0;
         }
相关问题