Question

I am getting this Index out of bound error when i am trying to add product with more than 1 quantity into order table. To be more clear, this is not the same case when I am adding a product with quantity 1 or multiple product each with quantity one. Code for inserting is below and error is displayed at sqlcommand line.

    SqlCommand command = new SqlCommand("Select Product_id,Product_name,Product_cost,Quantity from Cart where User_id='" + userid + "'",con);
       try
      { 
        con.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            int a = Convert.ToInt32(reader[0]);
            ar.Add(a);
            String pdname = reader[1].ToString();
            ar1.Add(pdname);
            Int32 pcost = Convert.ToInt32(reader[2]);
            ar2.Add(pcost);
            int q = Convert.ToInt32(reader[3]);
            ar3.Add(q);
        }
        pkid = (int[]) ar.ToArray(typeof(int));
        pkname = (String[]) ar1.ToArray(typeof(String));
        pkcost = (Int32[]) ar2.ToArray(typeof(int));
        pkq = (int[]) ar3.ToArray(typeof(int));
        con.Close();

       }
      catch (Exception ex)
       {
           Response.Write("Error at second" + ex);
       }
    con.Open();

        for (int i = total-1; i>=0; i--)
        {

   error here=:-         SqlCommand smd = new SqlCommand("Insert into Orders values('"+orderid+"','" 
            + userid + "','" + name + "','" + pkid[i] + "','" + pkname[i] + "','" 
            + address + "','" + pkq[i] + "','" + pkcost[i] + "','" + date + "','" 
            + payment.SelectedItem.ToString() + "','Pending')", con);

            smd.ExecuteNonQuery();

        }

        con.Close();
Was it helpful?

Solution 2

So after taking a look again at my code i got the problem and its just a simple one. Actually the total used in for loop is the sum of total quantity. In this case as i said i am submitting 1 product with quantity=2. So For loop is trying to get executed 2 times but total records their are 1 this is causing the problem. I just changed that total to Sum of total records and now its working fine. Thanks Everyone for helping.

OTHER TIPS

First set a breakpoint to pkid = (int[]) ar.ToArray(typeof(int)); pkname = (String[]) ar1.ToArray(typeof(String)); pkcost = (Int32[]) ar2.ToArray(typeof(int)); pkq = (int[]) ar3.ToArray(typeof(int)); these line and see the values in watch window. may be error must be in one of these lines.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top