2017-08-15 87 views
-1

我有從數據庫表讀取到datagrid的代碼,但它只運行一次,並將頂部行添加到數據庫中的數據網格。有沒有一種方法可以多次運行它來讀取不同行中的數據並將其添加到我的數據網格中。如何遍歷數據庫表以在datagrid中添加數據?

public static void AddData(DataGrid datagrid) 
{ 
     SqlConnection connect = GetConnection(); 
     SqlCommand command = new SqlCommand(); 
     command.Connection = connect; 

     //connect to database 
     connect.Open(); 
     command.CommandText = "Select req_status From TH_request where req_status = 'N'"; 
     command.ExecuteNonQuery(); 
     status = (String)command.ExecuteScalar(); 
     connect.Close(); 

     connect.Open(); 
     command.CommandText = "Select req_date_time From TH_request where req_status = 'N'"; 
     command.ExecuteNonQuery(); 
     time = (DateTime)command.ExecuteScalar(); 
     connect.Close(); 

     connect.Open(); 
     command.CommandText = "Select resp_user_name From TH_request where req_status = 'N'"; 
     command.ExecuteNonQuery(); 
     locationName = (String)command.ExecuteScalar(); 
     connect.Close(); 

     collection.Add(new DataObject() 
     { 
      A = time, 
      B = locationName, 
      C = status, 
      D = respUserName 
     }); 
     datagrid.ItemsSource = collection; 

} 
+2

Select語句之後,可能是多個字段名。 _Select req_status,req_date_time,resp_user_name from .... where ...._然後您使用SqlDataReader從返回的結果集中獲取字段。這是基本的ADO.NET編程。可能你應該停下來編寫一些代碼並查看ADO.NET的一些教程。 – Steve

+2

你應該*真的*從一些教程開始。當您只需要*一次*時,您已經查詢了數據庫*三次。把它包裝成一個循環就會多查詢一次。相反,查詢數據庫* once *以獲得您需要的完整結果集,然後將UI控件綁定到該結果集。 – David

+0

您的代碼將起作用。 DGV沒有更新,所以你需要使用一個技巧。只需datagrid.ItemsSource = null;然後datagrid.ItemsSource = collection; – jdweng

回答

0

您應該只需執行一次單個命令。然後,例如,你可以使用SqlDataReader爲這是從查詢返回的每一行創建一個DataObject

public static void AddData(DataGrid datagrid) 
{ 
    collection.Clear(); 
    using (SqlConnection connection = GetConnection()) 
    { 
     using (SqlCommand command = new SqlCommand("Select req_status, req_date_time, resp_user_name From TH_request where req_status = 'N'", connection)) 
     { 
      connection.Open(); 
      using (SqlDataReader reader = command.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        collection.Add(new DataObject() 
        { 
         A = Convert.ToDateTime(reader["req_date_time"]), 
         B = Convert.ToString(reader["resp_user_name"]), 
         C = Convert.ToString(reader["req_status"]), 
         D = respUserName 
        }); 
       } 

      } 
     } 
    } 
    datagrid.ItemsSource = collection; 
} 
+0

這工作非常感謝你。 – metadata