Reputation: 61
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 the 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);
//SqlParameter qty = comm.Parameters.AddWithValue("@qty", dataGridView2.Rows[i].Cells["7"].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;
}
// if (dataGridView2.Rows[i].Cells["7"].Value == null)
// {
// qty.Value = DBNull.Value;
// }
for (int q = 7; q <= dataGridView2.Columns.Count; q++) //dataGridView2.Columns.Count
{
int w = 1;
w++;
comm.Parameters.Add("@qty", SqlDbType.Int).Value = dataGridView2.Rows[w].Cells[q].Value;
comm.Parameters.Clear();
}
comm.ExecuteNonQuery();
comm.Parameters.Clear();
}
MessageBox.Show("Save SQL");
//try
//{
// comm.ExecuteNonQuery();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.ToString());
//}
}
}
Upvotes: 1
Views: 195
Reputation: 11841
In your for
loop you have:
comm.Parameters.Add("@qty", SqlDbType.Int).Value = dataGridView2.Rows[w].Cells[q].Value;
comm.Parameters.Clear();
So you are clearing all of the parameters you've previously added before you execute the query.
Upvotes: 1