变量名'@Order_id'已经被声明。变量名在查询批处理或存储过程中必须是唯一的

时间:2018-06-02 19:29:21

标签: c#

当我从gridview插入数据时出现此错误,我将数据插入到订单详细信息中,我希望在每个订单项目中保存相同的订单ID但不能。我在C#windows中开发。我在网上搜索但这无法解决我的问题。我被困在这一点上。任何帮助表示赞赏。

我正在添加我正在执行的代码行。

亲切的问候

SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;

cmd1.CommandText = "SELECT Top  1 *  FROM Purchase_Order Order By P_Order_ID desc";
cmd1.ExecuteNonQuery();

DataTable dt = new DataTable();

SqlDataAdapter sda2 = new SqlDataAdapter(cmd1);
sda2.Fill(dt);

int OrderID = 0;

foreach (DataRow dr2 in dt.Rows)
{
    OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());

    MessageBox.Show("order id +" +OrderID);
}

SqlCommand com2 = new SqlCommand();
com2.Connection = con;

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    foreach (DataRow dr2 in dt.Rows)
    {
        OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
    }

    string Query;
    Query = @"INSERT INTO Purchase_Order_Detail (P_Order_ID, ProductID, PSC_ID, Pack_ID, Color, Base_ID, Quantity) VALUES (@OrderID, @ProductID, @Sub_ID, @PackID, @Colors, @BaseID, @Quantity);";

    // com2.Parameters.Add("@OrderID" & dataGridView1.Rows(i).ToString(), dataGridView1(i));

    com2.Parameters.AddWithValue("@OrderID", OrderID);
    com2.Parameters.AddWithValue("@ProductID", dataGridView1.Rows[i].Cells[4].Value);
    com2.Parameters.AddWithValue("@Sub_ID", dataGridView1.Rows[i].Cells[6].Value);
    com2.Parameters.AddWithValue("@PackID", dataGridView1.Rows[i].Cells[8].Value);
    com2.Parameters.AddWithValue("@Colors", dataGridView1.Rows[i].Cells[9].Value);
    com2.Parameters.AddWithValue("@BaseID", dataGridView1.Rows[i].Cells[11].Value);
    com2.Parameters.AddWithValue("@Quantity", dataGridView1.Rows[i].Cells[13].Value);

    com2.CommandText = Query;
    com2.ExecuteNonQuery();

    //com2.Parameters.Clear();
}

1 个答案:

答案 0 :(得分:1)

您正在尝试重新添加已添加到SqlCommand的参数。在您的情况下,您应该在for()循环之前添加参数(和查询),然后使用新值填充这些参数以供执行。

SqlCommand com2 = new SqlCommand();
com2.Connection = con;
com2.CommandText = @"INSERT INTO Purchase_Order_Detail (P_Order_ID,ProductID,PSC_ID,Pack_ID,Color,Base_ID,Quantity) VALUES (@OrderID,@ProductID,@Sub_ID, @PackID,@Colors,@BaseID,@Quantity);";
com2.Parameters.Add("@OrderID", ...type...);
com2.Parameters.Add("@ProductID", ...type...);
com2.Parameters.Add("@Sub_ID", ...type...);
com2.Parameters.Add("@PackID", ...type...);
com2.Parameters.Add("@Colors", ...type...);
com2.Parameters.Add("@BaseID", ...type...);
com2.Parameters.Add("@Quantity", ...type...);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    foreach (DataRow dr2 in dt.Rows)
    {
        OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
    }
    com2.Parameters["@OrderId"].Value = OrderId;
    com2.Parameters["@ProductID"].Value = dataGridView1.Rows[i].Cells[4].Value;  
    ...        

    com2.ExecuteNonQuery();
}