【发布时间】:2019-04-05 07:15:04
【问题描述】:
我有这个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();
}
}
}
}
}
【问题讨论】:
-
错误信息与发布的代码不对应
-
MessageBox 弹出多次,因为它在一个 foreach 中,这是微不足道的还是我错过了什么?
-
@koviroli 我把代码的排列搞砸了吗?无论我从 datagridview 获得多少行,它都应该只弹出一次。
-
@meandyou 您的 MessageBox 将弹出与您的 datagridview 的行数一样的次数。如果您仔细观察,它在您的 foreach 循环内。
-
@koviroli 谢谢你让我知道。我在 foreach 循环的花括号之后更改了它。但是错误“参数化查询'(@id nvarchar(4000),@idtran nvarchar(4000),@qty nvarc'需要参数'@id',没有提供。”仍然没有修复。:(跨度>