怎样将DataGridView中显示的数据一次性保存到数据库中
颜挺帅 2010-08-04 04:50:53 string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\板材切割\Part.mdb";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
List<string> sqls = new List<string>();
try
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
Part_ID = dataGridView1.Rows[i].Cells[0].Value.ToString();
Length = Convert.ToSingle(dataGridView1.Rows[i].Cells[1].Value.ToString());
Width = Convert.ToSingle(dataGridView1.Rows[i].Cells[2].Value.ToString());
Depth = Convert.ToSingle(dataGridView1.Rows[i].Cells[3].Value.ToString());
Num = Convert.ToInt16(dataGridView1.Rows[i].Cells[4].Value.ToString());
Depict = dataGridView1.Rows[i].Cells[5].Value.ToString();
//string sql = string.Format("insert into Part values('{0}')", dataGridView1[0, i].Value .ToString());
string sql = "insert into Part(Part_ID,Length,Width,Depth,Num,Depict) values('" + Part_ID + "' ," + Length + " ," + Width + " ," + Depth + " ," + Num + " ,'" + Depict + "');";
//string sql = "insert into Part(Part_ID,Length,Width,Depth,Num,Depict) values('" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "' ," + Convert.ToSingle(dataGridView1.Rows[i].Cells[1].Value.ToString()) + " ," + Convert.ToSingle(dataGridView1.Rows[i].Cells[2].Value.ToString()) + " ," + Convert.ToSingle(dataGridView1.Rows[i].Cells[3].Value.ToString()) + " ," + Convert.ToInt16(dataGridView1.Rows[i].Cells[4].Value.ToString()) + " ,'" + dataGridView1.Rows[i].Cells[5].Value.ToString() + "');";
sqls.Add(sql);
}
}
catch (NullReferenceException ne)
{ MessageBox.Show(ne.Message.ToString()); }
//connection=new SqlConnection(...);
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
//connection.Open();
OleDbTransaction transaction = conn.BeginTransaction();
command.Transaction = transaction;//创建事务
try
{
foreach (string sql in sqls)
{
command.CommandText = sql;
command.ExecuteNonQuery();
}
//command.Transaction.Commit();
transaction.Commit();//提交事务
}
catch (Exception)
{
transaction.Rollback();//事务回滚,如果出错,恢复到操作前的状态
MessageBox.Show("未能保存");
}
finally
{
conn.Close();
}
}
我这个方法不对吗,为什么总是提示“未将对象引用设置到对象实例”