2012-02-29 82 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 =「堆棧溢出」;

相關問題