如何解决错误的“输入字符串格式不正确”的问题?

时间:2020-01-08 16:25:29

标签: c# asp.net

我的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:意外的令牌“单元格”

3 个答案:

答案 0 :(得分:0)

此错误表示您的字符串不是有效的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>");
}

您也可以参考Microsoft文档here以获得更多详细信息

答案 1 :(得分:0)

您可以使用Int32.TryParse

来消除错误。
if(!Int32.TryParse(qdata, out sr1)){
   MessageBox.Show(qdata + "is invalid number");
}

答案 2 :(得分:0)

代替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];

但是由于该列(或单元格)的visible属性设置为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,因为您将在“行创建”事件中对其进行动态设置。