You probably have the
AllowUserToAddRows[
^] property set to
true
, and you're inserting the values from the empty "insert" row. Check the
IsNewRow[
^] property before trying to insert the values.
You'll also want to fix the
SQL Injection[
^] vulnerability in your code.
And it would be best to open the connection once, rather than opening and closing it for every row.
const string Query = @"INSERT INTO Total ([Column1], [Column2], [Column3], [Date], [Receipt No], [Delivery Person], [Report], [Flavours], [Return])
VALUES (@Column1, @Column2, @Column3, @Date, @ReceiptNo, @DeliveryPerson, @Report, @Flavours, @Return)";
using (var connection = new OleDbConnection("..."))
using (var command = new OleDbCommand(connection, Query))
{
connection.Open();
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
var row = dataGridView1.Rows[j];
if (row.IsNewRow) continue;
command.Parameters.Clear();
command.Parameters.AddWithValue("@Column1", row.Cells[0].Value);
command.Parameters.AddWithValue("@Column2", row.Cells[1].Value)
command.Parameters.AddWithValue("@Column3", row.Cells[2].Value);
command.Parameters.AddWithValue("@Date", row.Cells[4].Value);
command.Parameters.AddWithValue("@ReceiptNo", label2.Text);
command.Parameters.AddWithValue("@DeliveryPerson", "---");
command.Parameters.AddWithValue("@Report", row.Cells[0].Value);
command.Parameters.AddWithValue("@Flavours", row.Cells[3].Value);
command.Parameters.AddWithValue("@Return", textBox66.Text);
command.ExecuteNonQuery();
}
}
Once you've fixed that, do yourself a favour and give your controls meaningful names, instead of accepting the default name that Visual Studio provides. You might remember what
textBox66
means
now, but when you come back to your code in a few months, you won't have a clue.