插入Datagridview行时的ROllback Commit

本文关键字:ROllback Commit Datagridview 插入 | 更新日期: 2023-09-27 18:26:29

这是我的代码,如果每行数据都不正确,那么所有行都会回滚我的代码问题是,当第一行可以时,它被插入数据库,但下一行不能和回滚不能工作

DateTime da = new DateTime();
da = DateTime.Now;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    using (DsourceDataContext dc = new DsourceDataContext())
    {
        using (TransactionScope tscope = new TransactionScope())
        {
            custompacking1 category = new custompacking1();
            {
                Double val3 = Convert.ToDouble(dataGridView1.Rows[i].Cells["fro"].Value);
                //Double val4 = Convert.ToDouble(dataGridView1.Rows[i].Cells["too"].Value.ToString());
                Double val5 = Convert.ToDouble(dataGridView1.Rows[i].Cells["gwt"].Value.ToString());
                Double val6 = Convert.ToDouble(dataGridView1.Rows[i].Cells["nwt"].Value.ToString());
                category.cid = Convert.ToInt32(dataGridView1.Rows[i].Cells["cid"].Value);
                category.tid = Convert.ToInt32(dataGridView1.Rows[i].Cells["tid"].Value);
                if (dataGridView1.Rows[i].Cells["fro"].Value != null)
                {
                    category.fro = Convert.ToDouble(dataGridView1.Rows[i].Cells["fro"].Value);
                }
                else
                {
                    category.fro = 0;
                }
                if (dataGridView1.Rows[i].Cells["too"].Value != null)
                {
                    category.too = dataGridView1.Rows[i].Cells["too"].Value.ToString();
                }
                else
                {
                    category.too = "";
                }
                if (dataGridView1.Rows[i].Cells["gwt"].Value != null)
                {
                    category.grosswt = Convert.ToDouble(dataGridView1.Rows[i].Cells["gwt"].Value);
                }
                else
                {
                    category.grosswt = 0;
                }
                if (dataGridView1.Rows[i].Cells["nwt"].Value != null)
                {
                    category.netwt = Convert.ToDouble(dataGridView1.Rows[i].Cells["nwt"].Value);
                }
                else
                {
                    category.netwt = 0;
                }
                category.date2 = dateTimePicker1.Value.ToString("MM/dd/yyyy");
                category.date1 = da.ToString("MM/dd/yyyy");
                category.gsmpcs = dataGridView1.Rows[i].Cells["gpcs"].Value.ToString();
            }
            dc.custompacking1s.InsertOnSubmit(category);
            dc.SubmitChanges();
            //dc.Dispose();
            tscope.Complete();
        }
    }
}
MessageBox.Show("Inserted");

在这个论坛的帮助下,我也使用transactionscope,但它不能工作

插入Datagridview行时的ROllback Commit

当然不会回滚,因为在插入DB时,如果所有值都不正确,就会发生回滚,但即使有一行是正确的,该值也会输入到DB中,在这种情况下,您必须在代码中手动执行回滚。使用"if"语句检查datarow1.fill()是否为true,如果返回false,则使用delete选项擦除最近受影响的行