I want to save multiple new rows from datagridview to database table at on click on btnsave please help me
What I have tried:
try
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Purchase_Order] (id,vcno,supid,cashcred,date,billno,supnm,prebal,totbal) VALUES (@val1,@val2,@val3,@val4,@val5,@val6,@val7,@val8,@val9)", con);
cmd.Parameters.AddWithValue("@val1", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@val2", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@val3", dataGridView1.Rows[i].Cells[2].Value);
cmd.Parameters.AddWithValue("@val4", dataGridView1.Rows[i].Cells[3].Value);
cmd.Parameters.AddWithValue("@val5", dataGridView1.Rows[i].Cells[4].Value);
cmd.Parameters.AddWithValue("@val6", dataGridView1.Rows[i].Cells[5].Value);
cmd.Parameters.AddWithValue("@val7", dataGridView1.Rows[i].Cells[6].Value);
cmd.Parameters.AddWithValue("@val8", dataGridView1.Rows[i].Cells[7].Value);
cmd.Parameters.AddWithValue("@val9", dataGridView1.Rows[i].Cells[8].Value);
lblsaved.Text = "Saved Success";
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (System.Data.SqlClient.SqlException es)
{
MessageBox.Show("Eror!" + es.Message, "Error");
}