我有此datagridview,需要在其中插入任何内容。所以我的datagridview中有2行。每当我单击“保存”按钮时,它都会询问我三次消息框。并且此错误出现在xcom.ExecuteNonQuery();
这是错误:
参数化查询'(@id nvarchar(4000),@ idtran nvarchar(4000),@ qty nvarc'需要参数'@id',其中 没有提供。
我检查了数据库,它从datagridview中插入了正确的行数。我想知道为什么消息框出现3次问我,然后出现错误。
请帮助我,我是C#的新手,仍然在学习。
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();
}
}
}
}
}
答案 0 :(得分:0)
这样的事情:(为了简单起见,我省略了消息框代码)
DataGridViewRow row;
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;"))
{
try
{
xcon.Open();
for (int n=0;n<dataGridView2.Rows.Count-1;n++)
{
row=dataGridView2.Rows[n];
using (SqlCommand xcom = new SqlCommand(query, xcon))
{
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();xcom.Dispose();
}
}
}
catch
{
//do what you need
}
finally
{
xcon.Close();
}
}
如果您在性能网格中的数据网格中有很多行,还请考虑this post。