Imran Khan

Imran Khan

  • NA
  • 9
  • 7.2k

how to insert gridView data into Database

May 19 2016 7:12 PM
i want to add the grid view data in data base in grid view i select the all item now all the item i want to save in database can anyone help me here is my gridview code
 
 
protected void btnSubmit0_Click(object sender, EventArgs e)
{


DataTable dt = new DataTable();

dt.Columns.Add("Product");
dt.Columns.Add("Qunatity");
dt.Columns.Add("UnitPrice");
dt.Columns.Add("total");


DataRow dr = null;
if (ViewState["sale"] != null)
{
for (int i = 0; i < 1; i++)
{
dt = (DataTable)ViewState["sale"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr["Product"] = ddlProduct.SelectedValue;
dr["Qunatity"] = Convert.ToInt32(txtQuantity.Text);
dr["UnitPrice"] = Convert.ToInt32(TxtUnitPrice.Text);
dr["total"] = Convert.ToInt32(TxtTotal.Text);


dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();

}

}
}

else
{
dr = dt.NewRow();
dr["Product"] = Convert.ToInt32(ddlProduct.SelectedValue);
dr["Qunatity"] = Convert.ToInt32(txtQuantity.Text);
dr["UnitPrice"] = Convert.ToInt32(TxtUnitPrice.Text);
dr["total"] = Convert.ToInt32(TxtTotal.Text);


dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();

}
ViewState["sale"] = dt;

 
 
and here is my database insert code
 
protected void btnSubmitDB_Click(object sender, EventArgs e)
{


foreach (GridViewRow row in GridView1.Rows)
{
string query = @"INSERT INTO sale_details(product_id,qty , unit_price , total )
values(@product_id,@qty ,@unit_price ,@total)";
db.con.Open();
db.com = new SqlCommand(query, db.con);

int pd = Convert.ToInt32((row.FindControl("Product")));
int qty = Convert.ToInt32((row.FindControl("Qunatity")));
int up = Convert.ToInt32((row.FindControl("UnitPrice")));
int tot = Convert.ToInt32((row.FindControl("total")));


db.com.Parameters.AddWithValue("@product_id", pd);
db.com.Parameters.AddWithValue("@qty", qty);
db.com.Parameters.AddWithValue("@unit_price", up);
db.com.Parameters.AddWithValue("@total", tot);


try
{
db.com.ExecuteNonQuery();
lblResult.Text = "Successfully data enter";
}
catch (Exception ex)
{
lblResult.Text = ex.Message;
}
finally
{

db.con.Close();
}

}

}

Answers (4)