将 PostgreSQL 数据库与文本文件进行比较时,wpf 数据网格中数据之间的空行

Empty rows between data in wpf datagrid when comparing PostgreSQL database with textfile

我正在尝试编写一个工具来比较数据库和文本文件。 它应该从 PostgreSQL 数据库获取数据并检查文本文件是否包含数据库列的值。

它应该显示数据库中的所有值,如果它们包含在文本文件中。 示例:如果名称 "a" 在文本文件中,它应该在 wpf 数据网格中显示 "a" 和数据库中的其他数据。

这是我的检查代码:

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

不知道哪里出错了,甚至方法不对。

提前感谢您的帮助。

为了防止出现空行,我创建了一个 if 子句,用于检查特定字符串是否为空。

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();
}

也许这会对遇到同样问题的其他人有所帮助。