I have this datagridview where I need to insert whatever it has on it. So I have 2 rows in my datagridview. Whenever I click the save button, it asks me the messagebox thrice. And this error comes out on the xcom.ExecuteNonQuery();
This is the error :
The parameterized query '(@id nvarchar(4000),@idtran nvarchar(4000),@qty nvarc' expects the parameter '@id', which was not supplied.
I checked the database and it inserts the right number of rows from the datagridview. I wonder why the message box goes out 3 times asking me and then followed by the error.
Please help me, I am new to c# and still learning.
private void button9_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView2.Rows)
{
string query = @"INSERT INTO MED (id,idtran,qty,user)
Values(@id,@idtran,@qty,@user)";
using (SqlConnection xcon = new SqlConnection(@"Server=MEAND;Database=SHC;Integrated Security=SSPI;"))
{
using (SqlCommand xcom = new SqlCommand(query, xcon))
{
xcon.Open();
xcom.CommandType = CommandType.Text;
xcom.Parameters.AddWithValue("@id", row.Cells["id"].Value);
xcom.Parameters.AddWithValue("@idtran", row.Cells["idtran"].Value);
xcom.Parameters.AddWithValue("@qty", row.Cells["qty"].Value);
xcom.Parameters.AddWithValue("@user", row.Cells["user"].Value);
xcom.ExecuteNonQuery();
try
{
DialogResult result1 = MessageBox.Show("Are you sure you want to save this?",
"Important Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result1 == DialogResult.Yes)
{
Medi b = new Medi();
b.Show();
this.Hide();
}
}
catch (Exception)
{
throw;
}
finally
{
xcon.Close();
}
}
}
}
}