2011-01-10 30 views
0

我想顯示數據從我的數據庫中的列到我的富文本框,但我越來越混合DataSet和DataReader之間 - 我知道下面的大多數代碼是正確的,我只是得到兩行包含錯誤,我不知道爲什麼:ADO.NET - DataRead錯誤

// Create a connection string 
      string ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\\Documents and Settings\\Harley\\Desktop\\Test.accdb"); 
      string SQL = "SELECT * FROM Paragraph"; 

      // create a connection object 
      SqlConnection conn = new SqlConnection(ConnectionString); 

      // Create a command object 
      SqlCommand cmd = new SqlCommand(SQL, conn); 
      conn.Open(); 

      DataTable dt = new DataTable(); 
      da.Fill(dt); //ERROR 

      // Call ExecuteReader to return a DataReader 
      SqlDataReader reader = cmd.ExecuteReader(); 

      foreach(DataRow reader in dsRtn) //ERROR 
      { 
       richTextBox = richTextBox.Text + reader[0].ToString(); 
      } 

      //Release resources 
      reader.Close(); 
      conn.Close(); 

     } 
+0

什麼錯誤信息? – 2011-01-10 18:51:54

回答

2

您的每個代碼段都有問題。

爲您提供此數據適配器實現:

 SqlCommand cmd = new SqlCommand(SQL, conn); 
     conn.Open(); 

     DataTable dt = new DataTable(); 
     da.Fill(dt); //ERROR 

你是不是你的SqlCommand對象與DataAdapter的關聯,因此不知道如何來填補你的數據表。

至於你的數據讀取器實現,

 // Call ExecuteReader to return a DataReader 
     SqlDataReader reader = cmd.ExecuteReader(); 

     foreach(DataRow reader in dsRtn) //ERROR 
     { 
      richTextBox = richTextBox.Text + reader[0].ToString(); 
     } 
您使用的是正確的DataReader試試這個

 // Call ExecuteReader to return a DataReader 
     SqlDataReader reader = cmd.ExecuteReader(); 

     while(reader.Read()) 
     { 
      richTextBox = richTextBox.Text + reader[0].ToString(); 
     }