2013-04-08 99 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

你必须在第一个例子中没有提及数据集。您需要将其传入或使其成为全局变量。

相关问题