I have two controls in my winform ,that is textboxes and datagridview .textboxes data entered by user save in one table(purchase) and datagridview data entered is save in another table (purchasedetail).My problem is textboxes values are saving in purchase table but datagridview values are not saving to database.
here is my save button code:
private void SAVE(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("insert into Purchase(purchase_id,purchase_date,ref_no,total,total_wrds) values(@purchase_id,@purchase_date,@ref_no,@total,@total_wrds)", con);
cmd.Parameters.AddWithValue("@purchase_id", textid.Text);
cmd.Parameters.AddWithValue("@purchase_date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("@ref_no", textrno.Text);
cmd.Parameters.AddWithValue("@total", texttotal.Text);
cmd.Parameters.AddWithValue("@total_wrds", textinwrds.Text);
cmd.ExecuteNonQuery();
foreach (DataGridViewRow row in datagrid.Rows)
{
if (!row.IsNewRow)
{
using(SqlCommand cmd11 = new SqlCommand("insert into Purchasedetail(product_id, product_name,qty,price,tax,discount,total)values(@product_id, @product_name,@qty,@price,@tax,@discount,@total)", con))
{
cmd11.Parameters.AddWithValue("@product_id", row.Cells[0].Value);
cmd11.Parameters.AddWithValue("@product_name", row.Cells[1].Value);
cmd11.Parameters.AddWithValue("@qty", row.Cells[2].Value);
cmd11.Parameters.AddWithValue("@price", row.Cells[3].Value);
cmd11.Parameters.AddWithValue("@tax", row.Cells[4].Value);
cmd11.Parameters.AddWithValue("@discount", row.Cells[5].Value);
cmd11.Parameters.AddWithValue("@total", row.Cells[6].Value);
cmd11.ExecuteNonQuery();
datagrid.Refresh();
//row.ReadOnly = true;
//clm.ReadOnly = true;
MessageBox.Show("Added Sucessfully", "OUTPUT", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}