[英]C# Read/Load multiple images for one row of info
該應用程序應顯示多行信息。 每行都有一些基本的字符串信息,以及一些參考圖像。 在 MySQL 數據庫中,我有表 A存儲基本信息,表 B存儲所有圖像路徑。 問題是,現在即使只有 1 行,Reader 讀取 3 次並創建 3 個 UserControl 幻燈片,這不是我想要的。 下面的簡化代碼:
string sql = "SELECT a.id, a.name, b.imgPath FROM a INNER JOIN b ON a.id=b.id";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
While(reader.Read())
{
UserControl userControl= new UserControl();
userControl.idLabel = reader.GetInt32("id").Tostring();
userControl.nameLabel = reader.GetString("name");
string imgPath = reader.GetString("imgPath");
Image img = New Image(...);
stackPanel.Children.Add(userControl);
}
如何解決這個問題? 非常感謝 !
不,它不會返回一行, join
會為每個連接對返回一行,因此您將獲得與圖片一樣多的行。 解決方案是檢查您是否已經為同一行添加了一個控件,在這種情況下檢索它並將新圖像添加到控件中,否則像您一樣創建新控件。
While(reader.Read())
{
string id = reader.GetInt32("id").ToString();
//Check if there is already a userControl for the current item id
UserControl userControl= stackPanel.Children.OfType<UserControl>().Where(uc => uc.idLabel == id).FirstOrDefault();
i( userControl == null)
{
userControl = new UserControl();
userControl.idLabel = id.Tostring();
userControl.nameLabel = reader.GetString("name");
stackPanel.Children.Add(userControl);
}
string imgPath = reader.GetString("imgPath");
Image img = New Image(...);
//Add the new image to your control. You haven't show how you add images to it.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.