在winform中使用while循环中的另一个SqlCommand

时间:2017-08-17 10:17:09

标签: c# sql-server foreach while-loop

当我评论dr.close时,我收到错误

  

已经有一个与此命令关联的打开DataReader,必须先关闭

但是当我取消注释读者时,我收到了这个错误:

  

读取器关闭时调用Read的尝试无效

我的代码:

foreach (DataGridViewRow row in datagridtempsale.Rows )
{
    string j = row.Cells[datagridsale.Columns["ItemId"].Index].Value.ToString();
    string k = row.Cells[datagridtempsale.Columns["ItemId"].Index].Value.ToString();

    bool z = k == j;

    if (z == true)
    {
        SqlCommand cmd2 = new SqlCommand("select TotalQuantity,TAmount from tbl_stock where ItemId=@id", d.con);
        cmd2.Parameters.AddWithValue("@id",row.Cells[datagridsale.Columns["ItemId"].Index].Value.ToString());

        d.con.Open();

        SqlDataReader dr = cmd2.ExecuteReader();

        while (dr.Read())
        {
            int m = int.Parse(dr["TotalQuantity"].ToString());
            decimal n = decimal.Parse(dr["TAmount"].ToString());

            SqlCommand cmd = new SqlCommand("update tbl_stock set TotalQuantity=@tq,TAmount=@ta where ItemId=@id", d.con);

            cmd.Parameters.Clear();

            string g = m.ToString();
            string f = row.Cells[datagridtempsale.Columns["ItemQuantity"].Index].Value.ToString();
            string i = n.ToString();
            string h = row.Cells[datagridtempsale.Columns["TotalPrice"].Index].Value.ToString();

            int x = (int.Parse(g) - int.Parse(f));
            decimal y = (decimal.Parse(i) - decimal.Parse(h));

            cmd.Parameters.AddWithValue("@tq", x);
            cmd.Parameters.AddWithValue("@ta", y);
            cmd.Parameters.AddWithValue("@id", row.Cells[datagridtempsale.Columns["ItemId"].Index].Value.ToString());

            dr.Close();
            cmd.ExecuteNonQuery();
            d.con.Close();
        }
    }
}

0 个答案:

没有答案