2012-02-29 79 views
0

我的代码是用于工作簿的创建者。表读错误:“对象引用未设置为对象的实例。”

该方法从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; 

} 

我得到的错误是:

对象引用不设置到对象的实例。

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

+0

错误发生在上面的哪一行代码? – Dinesh 2012-02-29 12:07:36

回答

0

,因为它说,你正在试图访问尚未实例化一个对象类。

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

比如你实例化_ currentQuestAllQuestions您之前尝试使用它们?

+0

现在感谢你的工作 – 2012-02-29 12:51:46

0

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

之前增加值你的问题,questionNumber等写

_currentQuest =新问题();

+0

另一件重要的事情!确保在循环的每个循环中创建一个新的_currentQuest实例。因此,将该行插入循环中。否则,你很可能只是从前覆盖你的实例,你的列表将包含n次相同的条目! – nothing9 2012-02-29 12:34:27

+0

现在感谢你的工作 – 2012-02-29 12:50:49

0

尝试实例化使用前每个对象与运营商。 您将通过调试了解该对象。请尝试调试并找出哪一行会引发错误。

0

它看起来像数据集是空的。这意味着您需要首先查看您的查询。它没有正确执行,因此mot填满了数据集,反过来没有任何行,当你开始你的foreach循环..它是抛出错误。为此,你可以调试你的代码,找出它到底在哪里抛出和异常。

0

对象引用错误是指一个或一个以上的对象有一个空值,您试图访问的方法或对象的属性。

可能有几个地方你的代码可以打破:

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; 

} 
2

访问类的属性/成员之前总是初始化类。

对于ex;

class objcls = null;

objcls = new class();

objcls.name =“堆栈溢出”;

相关问题