2015-04-14 60 views
-1

好日子,C#合併從SQL查詢結果中的datagridview

什麼我的工作,現在,是我有一個foreach循環,我會用槽的服務器列表的文件。每當它進入低谷時,它都會從文本文件提供的列表中查詢不同的服務器。結果顯示在datagridview中。但是現在每次查詢新的服務器時,它都會覆蓋已經在datagridview中的數據。我試圖合併數據表,但它不工作。任何想法?

try 
      { 
       String select = "select @@servername as Servername, @@servicename as Instance,SERVERPROPERTY('productversion') as Version, SERVERPROPERTY ('productlevel') as Level, SERVERPROPERTY ('edition') as Edition"; 
       cnn.Open(); 
       // MessageBox.Show ("Connection Open ! "); 
       MessageBox.Show("Connection established"); 



       SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cnn); 

       SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); 
       DataTable table = new DataTable(); 
       table.Locale = System.Globalization.CultureInfo.InvariantCulture; 
       dataAdapter.Fill(table); 
       dataGridView.DataSource = table; 
       table.Merge(table); 


       cnn.Close(); 


       //PaintRows(); 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Can not open connection ! " + ex); 
      } 
+0

這裏是你說你正在使用的循環代碼..這是有關您已發佈什麼below.also這是什麼'table.Merge(表)'當你調用填充方法是'表被填充..?如果是這樣的話,那麼你想要與現有的'table'合併的另一個表在哪裏呢? 「MessageBox.Show(」連接建立「);''''''''''''''''''''''''''''''''''''如果你使用調試器,你會知道它是否連接或不btw ..顯示所有相關的代碼.. – MethodMan

+0

你正在創建一個新的'DataTable'每次。你需要在你的循環之外聲明'DataTable',然後'dataAdapter.Fill(table);'行將在每次迭代中將結果附加到表中。 –

回答

0

問題是你需要追加到你的表中,但是你在每個循環迭代中都創建一個新的。

我會做的是:創建一個採用目標表變量的方法(因此它在每次調用中都是相同的)。

概要如下:

**** This code is somewhere to fill the table **** 
DataTable table = new DataTable(); 
foreach (line in file) 
{ 
    // Create connection to new server 
    cnn = ...; 

    // Append the results to the existing table 
    AppendSqlResults(table, cnn); 
} 

// Set the source AFTER collecting all the data 
dataGridView.DataSource = table; 

**** This method appends the data to the table **** 
public void AppendSqlResults(DataTable table, SqlConnection cnn) 
{ 
    cnn.Open(); 

    SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cnn); 

    SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); 
    table.Locale = System.Globalization.CultureInfo.InvariantCulture; 
    dataAdapter.Fill(table); 
    cnn.Close(); 
}