C#:对象引用未设置为对象的实例

时间:2010-04-27 08:09:21

标签: c# asp.net

我收到以下错误:

  

对象引用未设置为   对象的实例

这是我的C夏普代码:

      DataTable tableAcces = dsAcces.Tables["dsPrinterAcces"];
      DataTable tableMDF = dsAcces.Tables["dsPrinterMDF"];
      DataRow newrow = null;


      foreach(DataRow dr in tableAcces.Rows)
       {
           newrow = tableMDF.NewRow();

        newrow["PRINTER_ID"] = dr["PRINTER_ID"];
        newrow["MERK"] = dr["MERK"];
        newrow["MODEL"] = dr["MODEL"];
        newrow["LOKAAL_ID"] = dr["LOKAAL_ID"];

        tableMDF.Rows.Add(newrow);
      }

      daMDF.Update(dsMDF, "dsPrinterMDF");
      lblSucces.Text = "Gelukt. De tabel printers is overgezet.";
    }

在这一行中,他抛出错误:

newrow = tableMDF.NewRow();

非常感谢,

文森特

5 个答案:

答案 0 :(得分:2)

tableMDF则为null。您需要找出dsAcces.Tables["dsPrinterMDF"]在顶部返回null的原因。

答案 1 :(得分:0)

似乎dsAcces.Tables [“dsPrinterMDF”]返回null而不是表。也许找不到这张表,或者你有错字。

答案 2 :(得分:0)

看起来tableMDF为空,检查是否有表格dsPrinterMDF

答案 3 :(得分:0)

dsAcces.Tables["dsPrinterMDF"] 

似乎为null,因此请确保提供DataTable。我猜测标识符dsPrinterMDF不存在(例如,具有不同的大小写)

答案 4 :(得分:0)

这是我的所有代码:

  ng connStringAcces = ConfigurationManager.ConnectionStrings["RandAppAcces"].ToString();
  connAcces = new OleDbConnection(connStringAcces);


  daAcces = new OleDbDataAdapter();


  string sqlSelectAcces = "SELECT * FROM tblPrinter";
  OleDbCommand cmdAcces = new OleDbCommand(sqlSelectAcces, connAcces);
  daAcces.SelectCommand = cmdAcces;

  string connStringMDF = ConfigurationManager.ConnectionStrings["RandAppMDF"].ToString();
  connMDF = new SqlConnection(connStringMDF);

  daMDF = new SqlDataAdapter();

  string sqlSelectMDF = "SELECT * FROM tblPrinter";
  SqlCommand cmdMDF = new SqlCommand(sqlSelectMDF, connMDF);
  daMDF.SelectCommand = cmdMDF;

  string sqlInsertMDF = @"INSERT INTO tblPrinter(PRINTER_ID, MERK, MODEL, LOKAAL_ID)" +
    @"VALUES (@PRINTER_ID, @MERK, @MODEL, @LOKAAL_ID)";

  cmdMDF = new SqlCommand(sqlInsertMDF, connMDF);

  cmdMDF.Parameters.Add("@PRINTER_ID", SqlDbType.Int, 0, "PRINTER_ID");
  cmdMDF.Parameters.Add("@MERK", SqlDbType.NVarChar, 100, "MERK");
  cmdMDF.Parameters.Add("@MODEL", SqlDbType.NVarChar, 100, "MODEL");
  cmdMDF.Parameters.Add("@LOKAAL_ID", SqlDbType.Int, 0, "LOKAAL_ID");

   daMDF.InsertCommand = cmdMDF;

  dsMDF = new DataSet();
  dsAcces = new DataSet();

  daMDF.Fill(dsMDF, "dsPrinterMDF");
  daAcces.Fill(dsAcces, "dsPrinterAcces");

  DataTable tableAcces = dsAcces.Tables["dsPrinterAcces"];
  DataTable tableMDF = dsAcces.Tables["dsPrinterMDF"];
  DataRow newrow = null;


  foreach(DataRow dr in tableAcces.Rows)
   {
       newrow = tableMDF.NewRow();

    newrow["PRINTER_ID"] = dr["PRINTER_ID"];
    newrow["MERK"] = dr["MERK"];
    newrow["MODEL"] = dr["MODEL"];
    newrow["LOKAAL_ID"] = dr["LOKAAL_ID"];

    tableMDF.Rows.Add(newrow);
  }