这是我的代码,如果每行数据不正确,那么所有行都会回滚 我的代码问题是当第一行好了它插入数据库但接下来 不能和回滚无法正常工作
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");
m也可以在本论坛的帮助下使用Transactionscope,但它不能 工作
答案 0 :(得分:0)
当然它不会回滚,因为,当插入到DB中时,如果所有值都不正确,则会发生回滚,但即使一行是正确的,该值也会输入到DB中,在这种情况下,你会必须在代码中手动执行回滚。
使用&#39; if&#39;检查datarow1.fill()
的语句为true,如果返回false,则使用delete选项删除最近受影响的行