I import to Datagridview with Excel. Then I want to save this data to the SQL database, it saves, but at the end it gives an error:
Must declare the scalar variable "@ID".
Can I solve this?
private void btn_save_Click(object sender, EventArgs e) { //dataGridView1.ColumnCount = 6; foreach (DataGridViewRow row in dataGridView1.Rows) { string constring = @"Data Source=192.168.0.3\VADCASQL;Initial Catalog=dbexcel;User Id=sa;Password=***;"; for (int i = 0; i < dataGridView1.Rows.Count; i++) using (SqlConnection con = new SqlConnection(constring)) { using (SqlCommand cmd = new SqlCommand("INSERT INTO test VALUES(@ID, @Pavadinimas, @Kiekis, @Darbuotojas, @Papildymas, @Akcija)", con)) { if(dataGridView1.Rows[i].Cells[0].Value==null) { MessageBox.Show("XXXXXX"); //con.Close(); // this.Close(); //con.Open(); //cmd.ExecuteNonQuery(); //con.Close(); } else cmd.Parameters.AddWithValue("@ID", dataGridView1.Rows[i].Cells[0].Value); if (dataGridView1.Rows[i].Cells[1].Value == null) { cmd.Parameters.AddWithValue("@Pavadinimas", dataGridView1.Rows[i].Cells[1].Value = DBNull.Value); } else cmd.Parameters.AddWithValue("@Pavadinimas", dataGridView1.Rows[i].Cells[1].Value); if (dataGridView1.Rows[i].Cells[2].Value == null) { cmd.Parameters.AddWithValue("@Kiekis", dataGridView1.Rows[i].Cells[2].Value = DBNull.Value); } else cmd.Parameters.AddWithValue("@Kiekis", dataGridView1.Rows[i].Cells[2].Value); if (dataGridView1.Rows[i].Cells[3].Value == null) { cmd.Parameters.AddWithValue("@Darbuotojas", dataGridView1.Rows[i].Cells[3].Value = DBNull.Value); } else cmd.Parameters.AddWithValue("@Darbuotojas", dataGridView1.Rows[i].Cells[3].Value); if (dataGridView1.Rows[i].Cells[4].Value == null) { cmd.Parameters.AddWithValue("@Papildymas", dataGridView1.Rows[i].Cells[4].Value = DBNull.Value); } else cmd.Parameters.AddWithValue("@Papildymas", dataGridView1.Rows[i].Cells[4].Value); if (dataGridView1.Rows[i].Cells[5].Value == null) { cmd.Parameters.AddWithValue("@Akcija", dataGridView1.Rows[i].Cells[5].Value = DBNull.Value); } else cmd.Parameters.AddWithValue("@Akcija", dataGridView1.Rows[i].Cells[5].Value); con.Open(); cmd.ExecuteNonQuery(); con.Close();