我有网格视图,在那个网格视图中我有一个按钮,在选择该按钮时,我需要在数据表中插入/更新记录。如果在数据表中存在值,则 qty 字段将增加一。否则将在数据表中插入数量为 1 的新行。现在事情在 GridView1_RowCommand 我正在编写这段代码。但它在数据表中给了我错误的值。我的代码写在下面。请帮我。
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "datacommand")
{
DataTable dt = new DataTable();
if (Session["product_id"] != null)
{
dt = (DataTable)Session["product_id"];
}
DataRow dr;
//dt.Rows[0]["qty"] = data;
if (dt.Rows.Count<=0)
{
dt.Columns.Add("product_id", typeof(Int32));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("price", typeof(double));
dt.Columns.Add("total", typeof(double));
dr = dt.NewRow();
dr["product_id"] = e.CommandArgument;
dr["qty"] = 1;
dr["price"] = Convert.ToDouble(GridView1.Rows[0].Cells[3].Text);
dr["total"] = Convert.ToInt32(dr["qty"]) * Convert.ToDouble(dr["price"]);
dt.Rows.Add(dr);
dt.AcceptChanges();
Session["product_id"] = dt;
Response.Write("<script type='javacript'> One time</script>");
}
else
{
//dt = Session["product_id"];
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["product_id"].ToString() == e.CommandArgument)
{
dr = dt.NewRow();
dt.Rows[i]["qty"] = Convert.ToInt32(dt.Rows[i]["qty"])+ 1;
dt.Rows[i]["total"] = Convert.ToInt32(dt.Rows[i]["qty"]) * Convert.ToDouble(dt.Rows[i]["price"]);
Session["product_id"] = dt;
dt.AcceptChanges();
Response.Write(dt);
}
}
dr = dt.NewRow();
dr["product_id"] = e.CommandArgument;
dr["qty"] = 1;
dr["price"] = Convert.ToDouble(GridView1.Rows[0].Cells[3].Text);
dr["total"] = Convert.ToInt32(dr["qty"]) * Convert.ToDouble(dr["price"]);
dt.Rows.Add(dr);
dt.AcceptChanges();
Session["product_id"] = dt;
}
//GridViewRow row= e.CommandArgument
////DataColumn prodid = new DataColumn("product_id", typeof(System.Int32));
////dt.Columns.Add(prodid);
////DataColumn qty = new DataColumn("qty", typeof(System.Int32));
////dt.Columns.Add(qty);
//int index = Convert.ToInt32(e.CommandArgument);
//GridViewRow row = GridView1.Rows[index];
//AddShopCart(row.Cells[1].Text.ToString());
}
}