日期:2014-05-18  浏览次数:20726 次

昨天的问题一直还是没解决。datagridview数据保存
大虾们帮忙看看问题出在哪。
  DialogResult result = MessageBox.Show("确定要保存吗?", "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  ocnn = new OleDbConnection(connections);
  ocnn.Open();

  try
  {
  if (result == DialogResult.Yes)
  {
  for (int i = 0; i < dgv_Data.Rows.Count; i++)
  {
  string value1 = this.dgv_Data.Rows[i].Cells[0].Value.ToString();//已经有4条数据,好像这样写就不行了,但不知道怎么改
  string value2 = this.dgv_Data.Rows[i].Cells[1].Value.ToString();
  string value3 = this.dgv_Data.Rows[i].Cells[2].Value.ToString();
  string value4 = this.dgv_Data.Rows[i].Cells[3].Value.ToString();



  string sql = "insert into MIS_MaterielRegiser(MaterielRegiser_Number,MaterielRegiser_Name,MaterielRegiser_Model,MaterielRegiser_Unit) values('" + value1 + "','" + value2 + "','" + value3 + "','" + value4 + "')";
  ocmd = new OleDbCommand(sql, ocnn);
  // ocmd.ExecuteNonQuery();
  DataSet ds = new DataSet();
  oda = new OleDbDataAdapter(ocmd);


  dgv_Data.DataSource = null;
  dgv_Data.DataSource = ds.Tables[0];
  }
  }
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message); 
  }

------解决方案--------------------
1、try范围太大,调试时可以先去掉,之后只放到command执行时
2、string value1 = (this.dgv_Data.Rows[i].Cells[0].Value!=null)?this.dgv_Data.Rows[i].Cells[0].Value.ToString():string.Empty;
确定不为null
3、ocnn.Open();尽量放到,command执行前,并且尽快关闭
------解决方案--------------------
oda.Fill(ds)