+ -
当前位置:首页 → 问答吧 → 怎样将datagridview中的数据保存到数据库中???

怎样将datagridview中的数据保存到数据库中???

时间:2011-10-14

来源:互联网

麻烦各位帮我看看下面的代码哪儿有问题,老是报错“未将对象引用设置到对象的实例”
   

 

  public void baocun()
  {
  DataGridView mydataGridView = new DataGridView();
  mydataGridView = dataGridView1;

  try
  {
  DataTable dt = (DataTable)mydataGridView.DataSource;
  foreach (DataRow dr in dt.Rows)
  {
  switch (dr.RowState)
  {
  case DataRowState.Added:

  string xx = "";
  string aa = "";

  string KZT = null;
  string sql = "select columncode,columntype from KZT";
  OleDbDataAdapter dat = new OleDbDataAdapter(sql, oleDbConnection1);
  DataSet dst = new DataSet();
  dat.Fill(dst, "tabledetail");
  for (int i = 0; i < dst.Tables[0].Rows.Count; i++)
  {
  xx += "," + dst.Tables[0].Rows[i][0].ToString();
  aa += "," + "'" + dr[i].ToString() + "'";
  }

  string scmd = "insert into " + KZT + " ( " + xx + " ) values ( " + aa + ")";
  OleDbCommand myCommand = new OleDbCommand(scmd, oleDbConnection1);
  if (oleDbConnection1.State == System.Data.ConnectionState.Closed)
  {
  oleDbConnection1.Open();//打开数据库连接
  }
  myCommand.ExecuteNonQuery();
  //判断连接是否需要关闭
  if (oleDbConnection1.State == System.Data.ConnectionState.Closed)
  {
  //oleDbConnection1.Close();//关闭
  }
  break;
  }
  MessageBox.Show("保存数据成功!");
  }
  }
  catch (Exception ex)
  {
  MessageBox.Show("保存数据失败,请重试!" + ex.Message);
  return;
  }
  }

作者: hw2010201909   发布时间: 2011-10-14

你单步调试一下,看是哪一行出错,若是SQL语句有问题,把它打印出来后到pl/sql里执行一下就知道哪里错了

作者: rockyljt   发布时间: 2011-10-14

这个不是SQL的问题吧

作者: zengjc   发布时间: 2011-10-14

报错是:foreach (DataRow dr in dt.Rows) 中的 dt.Rows 对象没有实例化

作者: hw2010201909   发布时间: 2011-10-14

报错是:foreach (DataRow dr in dt.Rows) 中的 dt.Rows 对象没有实例化

作者: hw2010201909   发布时间: 2011-10-14

急求啊????????????????????????????????????????

作者: hw2010201909   发布时间: 2011-10-14

你这个是VS.Net(C#)程序啊,问题在于下面这句啊
DataTable dt = (DataTable)mydataGridView.DataSource;
mydataGridView.DataSource不能强制转换成DataTable吧

foreach (DataRow dr in dt.Rows)语法是对的,我们这么用都没有问题
  /// <summary>
  /// 在DataTable中根据指定的字段和其值返回第一个符合的DataRow,找不到匹配的行则返回null
  /// </summary>
  public static DataRow FindRow(ref DataTable dataTab, string colName, string strVal)
  {
  bool isFound = false;
  DataRow row2 = null;
  foreach (DataRow row1 in dataTab.Rows)
  {
  if (row1[colName].ToString() == strVal)
  {
  isFound = true;
  row2 = row1;
  break;
  }
  }
  if (isFound)
  return row2;
  else
  return null;
  }

作者: rockyljt   发布时间: 2011-10-14

热门下载

更多