2016-09-21 66 views
0

我正在嘗試編寫一個工具來比較數據庫與文本文件。 它應該從PostgreSQL數據庫中獲取數據,並檢查文本文件是否包含數據庫coloumn的值。將PostgreSQL數據庫與文本文件進行比較時,在wpf datagrid中的數據之間的空行

它應顯示數據庫中的所有值,如果它們包含在Textfile中。 示例:如果名稱「a」位於文本文件中,它應該在wpf數據網格中顯示數據庫中的「a」和其他數據。

這裏是我的ceck了代碼:

string connStr = "Server=" + Globals.server + ";Port=" + Globals.port + "; Database=" + Globals.db + ";User Id=" + Globals.user + ";Password=" + Globals.passwd + ";"; 
NpgsqlConnection conn = new NpgsqlConnection(connStr); 
conn.Open(); 
NpgsqlCommand nda = new NpgsqlCommand("select name,ip_address,location from public.\"smartq_devices\"", conn); 
using (StreamReader sr = File.OpenText(Globals.sFilename)) 
{ 
    string[] lines = File.ReadAllLines(Globals.sFilename); 
    for (int x = 0; x < lines.Length - 1; x++) 
    { 
     NpgsqlDataReader myReader = nda.ExecuteReader(); 
     while (myReader.Read()) 
     { 
      if (lines[x].Contains(myReader["name"].ToString())) 
      { 
       //MessageBox.Show(lines[x]); 
       DataRow newRow = dtResult1.NewRow(); 
       newRow["Hostname"] = myReader["name"].ToString(); 
       newRow["Ip address"] = myReader["ip_address"].ToString(); 
       newRow["Location"] = myReader["location"].ToString(); 
       dtResult1.Rows.Add(newRow); 
      } 
     } 
    } 
    dgViewDevices.ItemsSource = dtResult1.AsDataView(); 
} 

當我執行這個代碼,我得到的數據網格的一些數據,但它們之間存在一些空行。我添加了結果的圖片。

Datagrid with blank rows

我不知道我有錯誤,甚至是錯誤的做法。

非常感謝您的幫助。

+0

我相信你一定已經這樣做了,但我必須問:你確定在你的文本文件中沒有不必要的換行符嗎? –

+0

是的,我以前做過這個。但即使有空行,也不應該處理它們,因爲名稱不包含在這些行中? –

回答

0

爲了防止出現空行我做了一個if-clause,我檢查特定的字符串是否爲空。

if (newRow["Hostname"].ToString() != "") 
{ 
    dtResult1.Rows.Add(newRow); 
} 

添加此行後,數據網格中沒有空行。

全碼:

string connStr = "Server=" + Globals.server + ";Port=" + Globals.port + "; Database=" + Globals.db + ";User Id=" + Globals.user + ";Password=" + Globals.passwd + ";"; 
NpgsqlConnection conn = new NpgsqlConnection(connStr); 
conn.Open(); 
NpgsqlCommand nda = new NpgsqlCommand("select name,ip_address,location from public.\"smartq_devices\"", conn); 
using (StreamReader sr = File.OpenText(Globals.sFilename)) 
{ 
    string[] lines = File.ReadAllLines(Globals.sFilename); 
    for (int x = 0; x < lines.Length - 1; x++) 
    { 
     NpgsqlDataReader myReader = nda.ExecuteReader(); 
     while (myReader.Read()) 
     { 
      if (lines[x].Contains(myReader["name"].ToString())) 
      { 
       //MessageBox.Show(lines[x]); 
       DataRow newRow = dtResult1.NewRow(); 
       newRow["Hostname"] = myReader["name"].ToString(); 
       newRow["Ip address"] = myReader["ip_address"].ToString(); 
       newRow["Location"] = myReader["location"].ToString(); 
       if (newRow["Hostname"].ToString() != "") 
       { 
        dtResult1.Rows.Add(newRow); 
       } 
      } 
     } 
    } 
    dgViewDevices.ItemsSource = dtResult1.AsDataView(); 
} 

也許這將幫助其他,誰都有同樣的問題。

相關問題