日期:2014-05-17  浏览次数:21504 次

foreach 只循环了一次?
dgv,保存数据至数据库

            foreach (DataGridViewRow row in product.Rows)
             {
                     mxcom.Parameters.AddWithValue("@bh", row.Cells["编号"].Value);
                 mxcom.Parameters.AddWithValue("@cp", row.Cells["产品"].Value);
                 mxcom.Parameters.AddWithValue("@dj", row.Cells["单价"].Value);
                 mxcom.Parameters.AddWithValue("@dw", row.Cells["单位"].Value);
                 mxcom.Parameters.AddWithValue("@zk", row.Cells["折扣"].Value);
                 mxcom.Parameters.AddWithValue("@sl", row.Cells["数量"].Value);
                 mxcom.Parameters.AddWithValue("@hj", row.Cells["合计"].Value);
             }



这样写有错吗?怎么数据里面只保存了一条数据?新手不要见笑……

------解决方案--------------------
当你循环到第二次时,那些变量参数已经存在,你再赋值也只是把GridView中第二行的值覆盖第一行读取的值。
如此循环,全部读完,也只有你定义的那7个@变量,并且被覆盖赋值6次。
------解决方案--------------------
mxcom.Parameters.AddWithValue();
你仔细看看 这个方法
------解决方案--------------------
begingTrans();
for(int i= 0; i < count; i++)
{
     sql[i];
     foreach()
     {
         AddCmdParams()
     }
     Insert/Update(sql[i], params);
}
EndTrans()
------解决方案--------------------
在每次循环的时候new一个对象
------解决方案--------------------
这个循环只是在循环对对象进行赋值,赋值多少次,结果都只是最后一次结果值。再用这个对象去数据库执行保存,结果肯定是只有一条的。循环中进行保存好了,再用事务包一下。
------解决方案--------------------
引用:
dgv,保存数据至数据库

            foreach (DataGridViewRow row in product.Rows)
             {
mxcom=new mxcom();//这里要new 一个DbCommand
                     mxcom.Parameters.AddWithValue("@bh", row.Cells["编号"].Value);
                 mxcom.Parameters.AddWithValue("@cp", row.Cells["产品"].Value);
      &nb