通过调用存储过程插入两个或多个GridView行时出错

时间:2015-02-20 09:22:51

标签: c# stored-procedures gridview

我试图通过调用存储过程将GridView数据插入到表中。当GridView有一行时,代码工作正常,但是当它有多行时我怎么会收到错误。这个错误很奇怪,

  

过程或函数sp_InsertOrderDetail指定了太多参数。

private void inserOrderDetails()
{
conn = DB_Connect.GetConnection();

    if (validatition())
    {
        SqlCommand cmd = conn.CreateCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "[dbo].[sp_InsertOrderDetail]";

        foreach (GridViewRow row in grdRequest.Rows)
        {
            //cmd.Parameters.Add("@OrderID", SqlDbType.Int, 32, "OrderID").Value = row.Cells[0].Text;
            cmd.Parameters.Add("@OrderID", SqlDbType.Int, 32, "OrderID").Value = lblOrderID.Text;
            cmd.Parameters.Add("@ItemID", SqlDbType.Int, 32, "ItemID").Value = row.Cells[1].Text;

            try
            {
                if (conn.State.ToString() == "Closed")
                {
                    conn.Open();
                }
                cmd.ExecuteNonQuery();

                //WebMsgBox.Show("Sucessfully saved.");
            }
            catch (Exception ex)
            {
                WebMsgBox.Show("Saving failed." + ex);
            }

            conn.Close();
            //refresh();
        }
    }
    else
    {
        WebMsgBox.Show("Please, Fill all data fields before saving.");
    }
}

谢谢,干杯!

2 个答案:

答案 0 :(得分:1)

清除参数:

foreach (GridViewRow row in grdRequest.Rows)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@OrderID", SqlDbType.Int, 32, "OrderID").Value = lblOrderID.Text;
            cmd.Parameters.Add("@ItemID", SqlDbType.Int, 32, "ItemID").Value = row.Cells[1].Text;

答案 1 :(得分:0)

您不断向cmd中的foreach对象添加参数。

我将循环外的参数声明如下

cmd.Parameters.Add("@OrderID", SqlDbType.Int);
cmd.Parameters.Add("@ItemID", SqlDbType.Int);

然后在foreach中,做

cmd.Parameters["@OrderID"].Value = lblOrderID.Text;
cmd.Parameters["@ItemID"].Value = row.Cells[1].Text;