0

My 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>

My .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");
    }

I have use Add Wacth in Visual Studio, and i get this result
1.$exception {"Input string was not in a correct format."} System.FormatException
2.qdata = cell.Text This expression causes side effects and will not be evaluated
3.TableCell cell = GridView1.Rows[e.RowIndex].Cells[0]; error CS1073: Unexpected token 'cell'

  • `sr1 = Int32.Parse(qdata); //Wrong` Why do you `Parse` into `Int32` While `sr1` type is `string`? – Nguyễn Văn Phong Jan 08 '20 at 16:29
  • @Anonymous: No, the type of `sr1` is `int`. – Jon Skeet Jan 08 '20 at 16:29
  • Use `Int32.TryParse` instead. – Dai Jan 08 '20 at 16:30
  • This error means that your string (in your case qdata) is not a valid integer. To fix it, you can use ```TryParse``` – WilliamW Jan 08 '20 at 16:31
  • 1
    Could you please debug to watch the value of `qdata = cell.Text`. I'm afraid it's not a number – Nguyễn Văn Phong Jan 08 '20 at 16:31
  • @Anonymous `qdata` is a string –  Jan 08 '20 at 16:33
  • I see. But you should make sure that value of the `qdata ` is number. Ex: "1", "2", etc to be able to convert to `int`. Otherwise, you should use [Int32.TryParse](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netframework-4.8) – Nguyễn Văn Phong Jan 08 '20 at 16:35
  • @Anonymous actually i had debug and i get qdata = "" – Huiyong lee Jan 08 '20 at 16:37
  • `TryParse` is not going to magically make everything better. It will get rid of the exception, but that's about it. I'm guessing that's why everyone is proposing it. As the comments to the answer demonstrate, you can't just swap `Parse` with `TryParse` and everything works. You need to learn to program defensively. Assume everything you're getting from any source is invalid and program for that eventuality. – Heretic Monkey Jan 08 '20 at 16:47
  • problem fix if i use `TryParse`, but my product didn't be delete – Huiyong lee Jan 08 '20 at 17:05
  • That's because of your if statement. The ```dt.Rows[i].Delete()``` will be called **only** if sr == sr1. In your case, you mentioned your qdata was "". This means that your sr1 = 0. Check what is sr and don't hesitate to use breakpoints (your best friend when coding!) – WilliamW Jan 08 '20 at 17:10
  • i think the problem is come from `TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];`, because debugger show `error CS1073: Unexpected token 'cell' ` and `'qdata = cell.Text' threw an exception of type 'System.NullReferenceException'` – Huiyong lee Jan 08 '20 at 17:13

3 Answers3

0

This error means your string is not in a valid int format.

As pointed by Dai, you need to use 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>");
}

You can also refer to Microsoft documentation here to have more details

WilliamW
  • 438
  • 7
  • 18
  • `qdata.All(char.IsDigit))` won't work for values like `11111111111111111111111111111111` which is outside `Int32`'s range of values. Always use just `TryParse` and handle the `false` case. (As an aside rant, Microsoft **needs** to remove `Convert.ToInt32(String)` from the .NET Framework, it's burned too many programs - and is a bad habit too many people are still using today). – Dai Jan 08 '20 at 16:42
  • You **must** wrap the `Int32.TryParse` call in an `if()` statement because otherwise you cannot tell the difference between a valid `0` and a failure. – Dai Jan 08 '20 at 16:43
  • problem fixed, but i think the problem is come from `TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];`, because debugger show error `CS1073: Unexpected token 'cell'` and `'qdata = cell.Text' threw an exception of type 'System.NullReferenceException'` – Huiyong lee Jan 08 '20 at 17:11
0

You can get rid of the error by using Int32.TryParse

if(!Int32.TryParse(qdata, out sr1)){
   MessageBox.Show(qdata + "is invalid number");
}
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • i think the problem is come from `TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];`, because debugger show `error CS1073: Unexpected token 'cell' ` and `'qdata = cell.Text' threw an exception of type 'System.NullReferenceException'` – Huiyong lee Jan 08 '20 at 17:13
0

Instead of sr1 = Int32.Parse(qdata);

use TryParse as below (and you can combine condition in single 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;
}

UPDATE: Based on aspx code, I believe you are trying to read sno using the code:

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

But since that column's (or cell's) visible property is set to false, you will need to handle it differently. One of the ways is using DataKeyNames Property of GridView as shown below:

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

and in code behind, please remove the lines

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

and directly replace with below condition :

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

or since you know sno is int, you could directly cast to int. But it throws excpetion if its not int.

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

If you want to use Cells property, then an option is update the visiable property of "sno" on GridView Row Creation event. If you want to go with this option, you need to remove visible=false from asp:BoundField definition as you will be setting it dynamically in Row Creation event.

sam
  • 1,937
  • 1
  • 8
  • 14
  • @Huiyonglee I just copied those set of lines from your post and glad that main issue is resolved. Does this https://stackoverflow.com/questions/5648339/deleting-specific-rows-from-datatable help with your DataTable Delete issue? – sam Jan 08 '20 at 17:05
  • i think the problem is come from `TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];`, because debugger show `error CS1073: Unexpected token 'cell' ` and `'qdata = cell.Text' threw an exception of type 'System.NullReferenceException'` – Huiyong lee Jan 08 '20 at 17:10
  • @Huiyonglee are you using GridView control or Table control? Could you please post your .aspx page to assist further? Thank you in advance. I am just making a guess here that you are trying to assign GridView data to TableCell which is what causing the issue here. – sam Jan 08 '20 at 17:37
  • sure, check it. – Huiyong lee Jan 08 '20 at 17:39
  • Yes, im using gridview – Huiyong lee Jan 08 '20 at 17:47
  • @Huiyonglee Updated my post. Please verify. – sam Jan 08 '20 at 18:24
  • 1
    first method i get cannot convert object to string, so we need to create a object and make it `ToString()`, but second i cant success, btw problem is fixed, thank you – Huiyong lee Jan 08 '20 at 18:37
  • 2
    `if you use Convert functions, exceptions won't be thrown` - This statement is false. The Convert functions do throw exceptions. You should use `TryParse`. – Guilherme Jan 08 '20 at 18:44
  • @Guilherme If the parameter contains alphanumberic, then Convert function won't throw exception like int.Parse. Please try that. Convert function only throws exception if parameter is outside of int range and in which case obviously you don't use int32 functions. I meant that. – sam Jan 08 '20 at 19:12
  • 2
    @sam I'm not sure if I understand what you mean by "parameter contains alphanumeric", but I just tested `Convert.ToInt32("a");`, `Convert.ToInt32("1a");`, `Convert.ToInt32("");`, `Convert.ToInt32(" ");` and all of them throws `Input string was not in a correct format.` – Guilherme Jan 08 '20 at 19:26