【问题标题】:How do I solve get wrong 'input string was not in a correct format.'?如何解决错误的“输入字符串格式不正确。”?
【发布时间】:2020-01-09 03:33:49
【问题描述】:

我的 apsx

       <section class="sec1" style="height:100vh;">
            <link href="../Css/masterStyle.css" rel="stylesheet" />
            <link href="../Css/cartStyle.css" rel="stylesheet" />
        <h1>Cart</h1>
        <p class="sec1_p1">Your Food</p>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableTheming="True"  ShowFooter="True" OnRowDeleting="GridView1_RowDeleting" >
            <Columns>
                <asp:BoundField DataField="sno" HeaderText="sno" Visible="False" />
                <asp:BoundField DataField="restaurantID" HeaderText="restaurantID" Visible="False" />
                <asp:BoundField DataField="foodID" HeaderText="foodID" Visible="False">
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="foodName" HeaderText="Name">
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="foodPrice" HeaderText="Price">
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="quantity" HeaderText="Quantity">
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="totalPrice" HeaderText="Total ">
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:CommandField DeleteText="Remove" ShowDeleteButton="True" />
            </Columns>
            <HeaderStyle BackColor="#52E770" ForeColor="White" />
            </asp:GridView>
            <asp:Label ID="test" runat="server" Text="Label"></asp:Label>
        </section>

我的 .cs

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        DataTable dt = new DataTable();
        dt = (DataTable)Session["buyitems"];

        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            int sr;
            int sr1;
            string qdata;
            string dtdata;
            sr = Convert.ToInt32(dt.Rows[i]["sno"].ToString());
            TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
            qdata = cell.Text;
            dtdata = sr.ToString();
            sr1 = Int32.Parse(qdata); //fixed

            if (sr == sr1)
            {
                dt.Rows[i].Delete();
                dt.AcceptChanges();
                //Label1.Text = "Item Has Been Deleted From Shopping Cart";
                break;

            }
        }

        for (int i = 1; i <= dt.Rows.Count; i++)
        {
            dt.Rows[i - 1]["sno"] = i;
            dt.AcceptChanges();
        }

        Session["buyitems"] = dt;
        Response.Redirect("AddToCart.aspx");
    }

我在 Visual Studio 中使用了 Add Wacth,我得到了这个结果
1.$exception {"输入字符串的格式不正确。"} System.FormatException
2.qdata = cell.Text 这个表达式会产生副作用,不会被求值
3.TableCell 单元格 = GridView1.Rows[e.RowIndex].Cells[0];错误 CS1073:意外的令牌“单元格”

【问题讨论】:

  • sr1 = Int32.Parse(qdata); //Wrong 为什么你把Parse 变成Int32sr1 的类型是string
  • @Anonymous:不,sr1 的类型是int
  • 改用Int32.TryParse
  • 此错误意味着您的字符串(在您的情况下为 qdata)不是有效的整数。要修复它,您可以使用TryParse
  • 能否请您调试以查看qdata = cell.Text 的值。恐怕不是数字

标签: c# asp.net


【解决方案1】:

而不是sr1 = Int32.Parse(qdata);

使用 TryParse 如下(并且您可以在单个 if 中组合条件):

if (int.TryParse(qdata, out sr1) && sr == sr1)
{
     dt.Rows[i].Delete();
     dt.AcceptChanges();
     //Label1.Text = "Item Has Been Deleted From Shopping Cart";
     break;
}

更新: 基于aspx代码,相信你是在尝试使用代码读取sno:

TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];

但由于该列(或单元格)的可见属性设置为 false,因此您需要以不同的方式处理它。其中一种方法是使用 GridView 的 DataKeyNames 属性,如下所示:

<asp:GridView ID="GridView1" 
              runat="server" 
              AutoGenerateColumns="False" 
              EnableTheming="True"  
              ShowFooter="True" 
              OnRowDeleting="GridView1_RowDeleting" 
              DataKeyNames = "sno" >

在后面的代码中,请删除行

TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
qdata = cell.Text;

并直接替换为以下条件:

if (int.TryParse(GridView1.DataKeys[e.RowIndex].Value, out sr1) && sr == sr1)
{
     // code to hanlde this case goes here
}

或者因为你知道 sno 是 int,你可以直接转换为 int。但如果不是 int 则会抛出异常。

 int sno = (int) GridView1.DataKeys[e.RowIndex].Value; // since Value is [object datatype][1] 

如果您想使用 Cells 属性,则可以选择在 GridView Row Creation 事件中更新“sno”的可见属性。如果您想使用此选项,则需要从 asp:BoundField 定义中删除 visible=false,因为您将在 Row Creation 事件中动态设置它。

【讨论】:

  • @Huiyonglee 我刚刚从您的帖子中复制了这些行,很高兴主要问题得到了解决。这个stackoverflow.com/questions/5648339/… 对您的 DataTable 删除问题有帮助吗?
  • 我认为问题来自TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];,因为调试器显示error CS1073: Unexpected token 'cell' 'qdata = cell.Text' threw an exception of type 'System.NullReferenceException'
  • 我得到的第一个方法无法将对象转换为字符串,所以我们需要创建一个对象并使其成为ToString(),但第二个我不能成功,顺便说一句问题已解决,谢谢
  • if you use Convert functions, exceptions won't be thrown - 这个说法是错误的。 Convert 函数确实会引发异常。你应该使用TryParse
  • @sam 我不确定我是否理解“参数包含字母数字”的意思,但我刚刚测试了Convert.ToInt32("a");Convert.ToInt32("1a");Convert.ToInt32("");Convert.ToInt32(" "); 和所有他们抛出Input string was not in a correct format.
【解决方案2】:

此错误表示您的字符串不是有效的 int 格式。

正如 Dai 所指出的,您需要使用 TryParse:

var value = "test";
int number;
if (Int32.TryParse(value, out number))
{
   Console.WriteLine("Converted '{0}' to {1}.", value, number);         
}
else
{
   Console.WriteLine("Attempted conversion of '{0}' failed.", 
                      value ?? "<null>");
}

您也可以参考微软文档here 了解更多详情

【讨论】:

  • qdata.All(char.IsDigit)) 不适用于11111111111111111111111111111111 之类的值,它超出了Int32 的值范围。始终只使用TryParse 并处理false 案例。 (顺便说一句,微软需要从 .NET Framework 中删除 Convert.ToInt32(String),它烧毁了太多的程序 - 这是一个坏习惯,现在有太多人仍在使用)。
  • 必须Int32.TryParse 调用包装在 if() 语句中,否则您无法区分有效的 0 和失败。
  • 问题已修复,但我认为问题来自TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];,因为调试器显示错误CS1073: Unexpected token 'cell''qdata = cell.Text' threw an exception of type 'System.NullReferenceException'
【解决方案3】:

你可以使用Int32.TryParse来消除错误

if(!Int32.TryParse(qdata, out sr1)){
   MessageBox.Show(qdata + "is invalid number");
}

【讨论】:

  • 我认为问题来自TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];,因为调试器显示error CS1073: Unexpected token 'cell' 'qdata = cell.Text' threw an exception of type 'System.NullReferenceException'
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多