hello friends.
I am developing a shopping cart application in which customer will purchase item and the selected item will be displayed in his shopping cart through grid view.
My doubt is how to insert the values from the grid view into the database.
All the purchased items of customer should be inserted into the database.
thanks and regards.
解决方案Why? You fill the gridview from your code, using the session information (or possibly from cookies if your user must log in).
So why get the data back from where you wrote it and re-process it to make sure that it is correct and unmodified when you could just go back to the source data you wrote it from (which is in a DB friendly format anyway) and use that instead?
[edit]GridView, not Database, Griff :doh: - OriginalGriff[/edit]
use foreach to traverse through the values of the gridview and insert them into the database one row by row.
here is an example for you
protected void btnCheckout_Click(object sender, EventArgs e)
{
con.Open();
foreach(GridViewRow rowno in GridView1.Rows )
{
if (rowno.RowType == DataControlRowType.DataRow)
{
try
{
string productidnow = rowno.Cells[0].Text.ToString();
int quantitynow = int.Parse(((TextBox)rowno.Cells[2].FindControl("txtQuantity")).Text);
decimal pricenow = Convert.ToDecimal(rowno.Cells[3].Text.ToString());
decimal totalnow = Convert.ToDecimal(rowno.Cells[4].Text);
SqlCommand cmd = new SqlCommand("Insert into orders (productid, quantity , price, total) values (@productid,@quantity,@price,@total) ",con);
cmd.Parameters.AddWithValue("@productid", productidnow );
cmd.Parameters.AddWithValue("@quantity", quantitynow );
cmd.Parameters.AddWithValue("@price", pricenow );
cmd.Parameters.AddWithValue("@total", totalnow );
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
break;
}
}
}
}
here shopping cart items are inside the gridview. Now i have used foreach loop to traverse and add data to database for each row inside the gridview. hope it helps. Feel free to ask if u dont understand any part of the code.