我被卡住了。我一直在尝试不同的方法将6个头像字符串的结果加载到picturebox控件数组的加载方法中。
这就是我必须迭代(mysql结果集)值字符串到pictureboxes的内容
PictureBox[] avatars = { peer1, peer2, peer3, peer4, peer5, peer6 };
foreach (DataRow row in dt.Rows)
{
string url = "https://example.com/" + row["avatar"];
for (int i = 0; i < avatars.Length; i++)
{
avatars[i].Load(url);
}
}
但是每个图片框都显示为白色(空白)。如果我将SQL查询设置为LIMIT 1,我将为每个图片框获得相同的第一个头像。但它不会相应地分配,或者根本不会。
我如何才能循环到我的6个图片框正确的网址?谢谢你们
编辑
我也尝试过这样做,但没有运气
List<string> AvatarList = new List<string>();
PictureBox[] avatars = { peer1, peer2, peer3, peer4, peer5, peer6 };
foreach (DataRow row in dt.Rows)
{
AvatarList.Add("https://example.com/" + row["avatar"]);
}
for (int i = 0; i < AvatarList.Count; i++)
{
for (int x = 0; x < avatars.Length; x++)
{
avatars[x].Load(AvatarList[i]);
}
}
PictureBox[] avatars = { peer1, peer2, peer3, peer4, peer5, peer6 };
foreach (var pb in avatars)
{
foreach (DataRow row in dt.Rows)
{
string url = "https://example.com/" + row["avatar"];
pb.Load(url);
}
}
已解决
在这种类似的情况下阅读,答案如下
private bool CacheReadAvatars = true; // Image caching?
PictureBox[] avatars = { peer1, peer2, peer3, peer4, peer5, peer6 };
foreach (DataRow row in dt.Rows)
{
if (CacheReadAvatars != false)
{
SaveImage("https://example.com/" + row["avatar"], CachePath + "/peer_" + row["user_id"] + ".jpg");
AvatarList.Add(CachePath + "/peer_" + row["user_id"] + ".jpg");
}
else
{
AvatarList.Add("https://example.com/" + row["avatar"]);
}
}
for (int i = 0; i < AvatarList.Count; i++)
{
if (CacheReadAvatars != false)
{
avatars[i].Image = Image.FromFile(AvatarList[i]);
}
else
{
avatars[i].Load(AvatarList[i]);
}
}
public void SaveImage(string imageUrl, string filename)
{
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
Bitmap bitmap; bitmap = new Bitmap(stream);
if (bitmap != null)
{
bitmap.Save(filename, ImageFormat.Jpeg);
}
stream.Flush();
stream.Close();
client.Dispose();
}
我冒昧地允许图像缓存,以防我想限制HTTP请求、数据使用等。
为什么要使用双回路?如果图像的URL是正确的,那么下面的代码应该可以工作。
PictureBox[] avatars = { peer1, peer2, peer3, peer4, peer5, peer6 };
int i = 0;
foreach (DataRow row in dt.Rows)
{
string url = "https://example.com/" + row["avatar"];
avatars[i].Load(url);
i++;
}