Programming for Everybody: C#: Insert all data of a dataGridView to database at once with database with source code

C#: Insert all data of a dataGridView to database at once with database with source code




private void button8_Click(object sender, EventArgs e)

        {

            foreach(DataGridViewRow row in dataGridView1.Rows)

            {

                string constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:/ddd.accdb";

                using (OleDbConnection con = new OleDbConnection(constring))

                {


                    using (OleDbCommand cmd = new OleDbCommand(" INSERT INTO table1 ([ID], [firstname],[lastname],[sum]) VALUES (@id,@firstname,@lastname,@sum)", con))

                    {



                        cmd.Parameters.AddWithValue("@id", row.Cells["ID"].Value);


                        cmd.Parameters.AddWithValue("@firstname", row.Cells["firstname"].Value);

                        cmd.Parameters.AddWithValue("@lastname", row.Cells["lastname"].Value);


                        cmd.Parameters.AddWithValue("@sum", row.Cells["sum"].Value);



                        con.Open();

                        cmd.ExecuteNonQuery();

                        con.Close();

                    }

                 

                    }

              


                }



            MessageBox.Show("All rows inserted");

         

           

        } 

1 comment:

  1. I receive this error:
    System.Data.OleDb.OleDbException: '@id_student parameter has no default value.'

    ReplyDelete