Inserting values from DataGridView to database C#

Inserting datGridView all rows to database:

We know to inserting values from textboxes and other data entry controls to database
but the values enter from dataGridView to database is little different than those ways
because here we have to insert all the rows which contains in dataGridView to database.
Click here for inserting values from textboxes to the datagridview control.So for the we
have to run a loop to to collect all the data from the all the rows from the database.



Event : The event to raise this code is saveButton_Click

OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\naresh\My stuff\Thal tre tsks trim\Thalassemia\Data\thalsemia.accdb");
con.Open();

for (int i = 0; i < dataGridView1.Rows.Count; i++)

{

   OleDbCommand cmd= new OleDbCommand("INSERT INTO table1(name,number,salory,) VALUES
 ('"+dataGridView1.Rows[i].Cells["Column1"].Value+"','"+dataGridView1.Rows[i].Cells["Column2"].Value+"',
'"+dataGridView1.Rows[i].Cells["Column3"].Value+" ' ",con);

   cmd.ExecuteNonQuery();

}

con.Close();



I hope this code will help you.

1 comment:

  1. Hi thanks for your codes it really helped me on my project. Therefore to correct on what you've done :
    SqlCommand cmd = new SqlCommand("INSERT INTO table1(name, surname, number, salary) VALUES(" + metroGrid1.Rows[i].Cells["Column1"].Value + ",'" + metroGrid1.Rows[i].Cells["Column2"].Value + "','" + metroGrid1.Rows[i].Cells["Column3"].Value + "','" + metroGrid1.Rows[i].Cells["Column3"].Value + "')", con);

    ReplyDelete