0

I am trying to store my gridview into a database but I can't seem to do it. How should I solve it?

foreach (GridViewRow row in gv_CartView.Rows)
{
    int quantity = Convert.ToInt32(row.Cells[2].Text);
    Session["Quantity"] = quantity;

    decimal TotalPrice = Convert.ToDecimal(row.Cells[4].Text);
    Session["TotalPrice"] = TotalPrice;

    string queryStr = "INSERT into Cart (prod_Id,prod_Name,qty,prod_Price,total_Amt)"
    + "values (@ItemID,@Product_Name,@Quantity,@Product_Price,@TotalPrice)";
    SqlConnection conn = new SqlConnection(_connStr);
    SqlCommand cmd = new SqlCommand(queryStr, conn);
    cmd.Parameters.AddWithValue("@ItemID", row.Cells[0].Text);
    cmd.Parameters.AddWithValue("@Product_Name", row.Cells[1].Text);
    cmd.Parameters.AddWithValue("@Quantity", Convert.ToInt32(row.Cells[2].Text));
    cmd.Parameters.AddWithValue("@Product_Price", Convert.ToDecimal(row.Cells[3].Text));
    cmd.Parameters.AddWithValue("@TotalPrice", Convert.ToDecimal(row.Cells[4].Text));

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}

I get this error:

"Input string was not in a correct format"

from the following lines and I have changed the codes many times but it still does not work.

cmd.Parameters.AddWithValue("@Quantity", Convert.ToInt32(row.Cells[2].Text));
cmd.Parameters.AddWithValue("@Product_Price", Convert.ToDecimal(row.Cells[3].Text));
cmd.Parameters.AddWithValue("@TotalPrice", Convert.ToDecimal(row.Cells[4].Text)); 
Draken
  • 3,134
  • 13
  • 34
  • 54
jiiiv
  • 1
  • 2
  • 4
    The error states that one of the values in your cell is not convertible to integer or decimal. – Renatas M. Jul 27 '18 at 13:17
  • Don't use `Convert`, it's just a call to `int.Parse` or `decimal.Parse` that doesn't allow you to specify additional parameters like CultureInfo. – Panagiotis Kanavos Jul 27 '18 at 13:35
  • The error comes from the attempt to *parse* the cell text. Most likely the user entered a decimal value with a separator used in one locale while the *web app* runs on a different locale. Eg, entered `1,5` when the web app is configured for `en-US`. – Panagiotis Kanavos Jul 27 '18 at 13:36

0 Answers0