2013-04-08 39 views
1

爲什麼Method無法使用數據集向數據庫發送值?非靜態字段,方法或屬性(數據集)需要對象引用

Here is example

實施例,錯誤

public string dane() 
     { 
      // Get the DataTable of a DataSet. 

      DataTable table = DataSet1.Tables["Products"]; 
      DataRow[] rows = table.Select(); 

      string s =""; 
      // Print the value one column of each DataRow. 
      for (int i = 0; i < rows.Length; i++) 
      { 
       s += rows[i]["ProductID"] + " "; 
      } 

      return s; 

     } 

錯誤 - 一個對象引用是所必需的非靜態字段,方法或屬性

它`不可能找到數據。 (但錯誤被固定)

public string dane() 
{ 
    // Get the DataTable of a DataSet. 
    DataSet1 dataSet = new DataSet1(); 
    DataTable table = dataSet.Tables["Products"]; 
    DataRow[] rows = table.Select(); 

    string s =""; 
    // Print the value one column of each DataRow. 
    for (int i = 0; i < rows.Length; i++) 
    { 
     s += rows[i]["ProductID"] + " "; 
    } 

    return s; 

} 

enter image description here

回答

3

那是因爲你的DataSet1類是可能不是靜態的,但我們不知道,因爲你沒有告訴我們。如果不先創建DataSet1對象,則不能引用Tables。我想你在這裏得到的錯誤:

DataTable table = DataSet1.Tables["Products"]; 

而在你的第二個代碼示例,您實際創建的DataSet它解決了錯誤的實例。

您可以讓您的修復或使DataSet1靜態的,但在這種情況下,它似乎並不認爲這將是一個很好的解決方案。

+0

是的,但爲什麼我無法獲得任何數據?使用第二個代碼? – 2013-04-08 14:54:32

+0

@ Rafael-JuniorMVCDeveloper你是否瀏覽過你的代碼,並確認'rows'實際上包含任何東西,然後再執行'table.Select()'? – tnw 2013-04-08 14:59:56

+0

它顯示我我有0行,但在數據庫中我有數據。 – 2013-04-08 15:01:46

1

你必須在第一個例子中沒有提及數據集。您需要將其傳入或使其成爲全局變量。

相關問題