繁体   English   中英

表读取错误:“对象引用未设置为对象的实例。”

[英]error in table reading :“Object reference not set to an instance of an object.”

我的代码是为工作簿创建者。

该方法从DB中获取问题并将其放入列表中。

我正在尝试将数据放入我的问题列表中,我有一个问题类和一个getpageDB方法,但仍然得到错误“对象引用未设置为对象的实例”。

public DataSet getPageDB(string myQuery, string ConnStr)
{


   OleDbDataAdapter oda = new OleDbDataAdapter   (myQuery, ConnStr);
    DataSet ds = new DataSet();
    oda.Fill(ds);

    foreach(DataRow pRow in ds.Tables[0].Rows){


        _currentQuest.question=pRow["question"].ToString();
        _currentQuest.questionNumber =Convert.ToInt16( pRow["questionnumber"]);
        _currentQuest.rightAnswer=pRow["answer"].ToString();
        _currentQuest.goodFeedBack=pRow["goodfeedback"].ToString();
        _currentQuest.badFeedBack1=pRow["badfeedback1"].ToString();
         _currentQuest.badFeedBack2=pRow["badfeedback2"].ToString();
        AllQuestions.Add(_currentQuest);


    }
    return ds;

}

我得到的错误是:

你调用的对象是空的。

这个错误是什么意思? 问题是什么?

始终在访问类的属性/成员之前初始化类。

对于前

class objcls = null;

objcls = new class();

objcls.name =“堆栈溢出”;

正如它所说,您正在尝试访问尚未实例化的对象类。

尝试在调试中运行以查看哪一行引发错误。

例如,在尝试使用它们之前,您是否已实例化_ currentQuestAllQuestions

你总是需要一个新的_currentQuest Instnace!

在为您的问题添加值之前,questionNumber等会写入

_currentQuest = new Question();

尝试在使用NEW运算符之前实例化每个对象。 您可以通过调试了解该对象。 请尝试调试并找到哪一行抛出错误。

数据集似乎是空的。 这意味着您需要先查看您的查询。 它没有正确执行,因此mot填充数据集,而数据集又没有任何行,当你启动foreach循环时,它就是抛出错误。 为此,您可以调试代码并找出它的确切位置和异常。

对象引用错误意味着您的一个或多个对象的值为null,并且您正在尝试访问该对象的方法或属性。

您的代码可能有多个地方可能会破坏:

public DataSet getPageDB(string myQuery, string ConnStr)
{
    OleDbDataAdapter oda = new OleDbDataAdapter   (myQuery, ConnStr);
    DataSet ds = new DataSet();
    oda.Fill(ds);

    foreach(DataRow pRow in ds.Tables[0].Rows){ //here if there are no tables in the dataset. So you must check if(ds.Tables.Count > 0) before executing the for loop.

         //What is _currentQuest? Have you initialised it with a new keyword? Is it null when you try to use it?
        _currentQuest.question=pRow["question"].ToString();
        _currentQuest.questionNumber =Convert.ToInt16( pRow["questionnumber"]);
        _currentQuest.rightAnswer=pRow["answer"].ToString();
        _currentQuest.goodFeedBack=pRow["goodfeedback"].ToString();
        _currentQuest.badFeedBack1=pRow["badfeedback1"].ToString();
        _currentQuest.badFeedBack2=pRow["badfeedback2"].ToString();

        //What is AllQuestions? make sure that this is not null.
        AllQuestions.Add(_currentQuest);

    }
    return ds;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM