如何用2个表中的数据填充一个C#窗体窗体列表视图?
我正在做一个“加载”按钮来加载SQL数据库中的所有数据,将它们放入列表视图中。如何用2个表中的数据填充一个C#窗体窗体列表视图?
if(lstEnsemble.Items.Count == 0)
{
MySqlConnection connexion = OpenConnection();
MySqlCommand reqRemplissageClient = new MySqlCommand("select * from client order by idClient ASC;", connexion);
MySqlCommand reqRemplissagePanne = new MySqlCommand("select * from Panne order by idClient ASC;", connexion);
MySqlDataReader resultatClient = reqRemplissageClient.ExecuteReader();
MySqlDataReader resultatPanne = reqRemplissageClient.ExecuteReader();
while (resultatClient.Read() && resultatPanne.Read())
{
ListViewItem item = new ListViewItem(resultatClient["nomCli"].ToString());
item.SubItems.Add(resultatClient["prenomCli"].ToString());
if (resultatClient["idClient"] == resultatPanne["idClient"])
{
item.SubItems.Add(resultatPanne["appareil"].ToString());
}
item.SubItems.Add(resultatClient["villeCli"] + " " + resultatClient["cpCli"] + " " + resultatClient["rueCli"]);
item.SubItems.Add(resultatClient["telCli"].ToString());
if (resultatClient["idClient"] == resultatPanne["idClient"])
{
item.SubItems.Add(resultatPanne["description"].ToString());
item.SubItems.Add(resultatPanne["dateEntree"].ToString());
}
item.SubItems.Add(resultatClient["mailCli"].ToString());
lstEnsemble.Items.Add(item);
}
CloseConnection(connexion);
}
这显然不起作用,但我无法设法找到另一种方法来做到这一点。 我试图分别做两个请求,但我又错过了这个逻辑。
在你的问题中,你不完全清楚你正在使用什么样的数据。看来你假设(或更好的希望)idClient
值完全匹配在两个表中。
我假定你真正想做一个JOIN
。如果不是这样,我会再次删除这篇文章。
所以,你应该用一个JOIN
做只有一个查询:
if(lstEnsemble.Items.Count == 0)
{
string sql = @"SELECT nomCli, prenomCli, appareil, villeCli, rueCli,
cpCli, telCli, description, dateEntree, mailCli
FROM client LEFT JOIN Panne ON (client.idClient = Panne.idClient)";
MySqlConnection connexion = OpenConnection();
MySqlCommand request = new MySqlCommand(sql, connexion);
MySqlDataReader resultat = requestExecuteReader();
while (resultat.Read())
{
ListViewItem item = new ListViewItem(resultat["nomCli"].ToString());
item.SubItems.Add(resultat["prenomCli"].ToString());
item.SubItems.Add(resultat["appareil"].ToString());
item.SubItems.Add(resultat["villeCli"] + " " + resultat["cpCli"] + " " + resultat["rueCli"]);
item.SubItems.Add(resultat["telCli"].ToString());
item.SubItems.Add(resultat["description"].ToString());
item.SubItems.Add(resultat["dateEntree"].ToString());
item.SubItems.Add(resultat["mailCli"].ToString());
lstEnsemble.Items.Add(item);
}
CloseConnection(connexion);
}
但是你应该知道,在client
与Panne
没有匹配行的行会出现在结果null
值。因此,您需要首先在列索引(sql查询中的位置)上使用resultat.IsDbNull()
来检查它们。
或者,您可以使用INNER JOIN
而不是LEFT JOIN
来仅获取两个表中存在的行。
我感觉迟缓。我完全忘记了你可以加入桌子。非常感谢您的快速回答!祝你今天愉快 – Fenwyr
你应该改变一些东西的话,就变得很容易。
- 做一个简单的SQL查询。只需加入你的表格并选择你需要的东西。
- 将数据库访问分开填充您的列表视图。把你的结果放在一个数组或数据表中。
- 使用可用的数据,您可以轻松地绑定它或遍历它以生成ListViewItems。
也谢谢你,我忘记了你可以加入表格......对我感到羞耻 – Fenwyr
你是否认为/ _hope_那个'idClient'完全匹配两个表?或者是否可以并且有效地将行与不同的'idClient'值组合起来? –