Click here to Skip to main content
15,888,283 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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");
}
Posted
Updated 15-Mar-16 8:45am
Comments
ZurdoDev 15-Mar-16 14:29pm    
What doesn't work?
Sascha Lefèvre 15-Mar-16 14:54pm    
Please tell the error message.

1 solution

Your code seems fine, but lots of things can go wrong in the database with null values, constraints etc., so the exact error message would be helpful.

Here is an interesting article that might help you:
Auto Saving DataGridView Rows to a SQL Server Database[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900