I am new to C#. My problem is I want to insert the ean, description, bookcode, price and discount into SQL Server with the qty from column 7 and above:
My current code is able to insert the data but the quantity is already defined. I am thinking to do looping, but I got an error "Must declare scalar variable" and I'm not sure my logic is correct.
Here's a screenshot of my SQL Server table:

My code:
- private void button3_Click(object sender, EventArgs e) {
- using (SqlConnection conn = new SqlConnection(";Trusted_Connection=False"))
- using (SqlCommand comm = new SqlCommand())
- {
- comm.Connection = conn;
- conn.Open();
- for (int i = 1; i < dataGridView2.Rows.Count; i++) {
- comm.CommandText = "INSERT INTO SOLine (CustID,Bookcode,Barcode,Description,Price,Disc,Qty) VALUES ('2058 KBC',@bookcode,@barcode,@desc,@price,@disc,@qty)";
- SqlParameter bookcode = comm.Parameters.AddWithValue("@bookcode", dataGridView2.Rows[i].Cells["BOOKCODE"].Value);
- SqlParameter barcode = comm.Parameters.AddWithValue("@barcode", dataGridView2.Rows[i].Cells["3"].Value);
- SqlParameter desc = comm.Parameters.AddWithValue("@desc", dataGridView2.Rows[i].Cells["4"].Value);
- SqlParameter price = comm.Parameters.AddWithValue("@price", dataGridView2.Rows[i].Cells["5"].Value);
- SqlParameter disc = comm.Parameters.AddWithValue("@disc", dataGridView2.Rows[i].Cells["6"].Value);
-
-
- if (dataGridView2.Rows[i].Cells["BOOKCODE"].Value == null) { bookcode.Value = DBNull.Value; }
- if (dataGridView2.Rows[i].Cells["3"].Value == null) { barcode.Value = DBNull.Value; }
- if (dataGridView2.Rows[i].Cells["4"].Value == null) { desc.Value = DBNull.Value; }
- if (dataGridView2.Rows[i].Cells["5"].Value == null) { price.Value = DBNull.Value; }
- if (dataGridView2.Rows[i].Cells["6"].Value == null) { disc.Value = DBNull.Value; }
-
-
- for (int q = 7; q <= dataGridView2.Columns.Count; q++)
- int w = 1;
- w
- w++;
- comm
- comm.Parameters.Add("@qty", SqlDbType.Int).Value = dataGridView2.Rows[w].Cells[q].Value;
- comm
- comm.Parameters.Clear();
- } comm.ExecuteNonQuery();
- comm
- comm.Parameters.Clear();
- }
- MessageBox.Show("Save SQL");
-
-
-
-
-
-
-
-
-
- }
- }