【发布时间】:2017-12-20 14:01:11
【问题描述】:
在我的 MySQL 数据库中存储了图像。我现在可以显示这些图片。但不幸的是,我的代码只适用于一张图片。我想显示表格中的所有图片,但使用rdr.Nextresult() 不起作用。
我有一个 PicutreBox 数组:
PictureBox[] pictureboxes = new PictureBox[30];
我为每个索引生成新的图片框:
for (int i = 0; i < pictureboxes.Length; i++)
{
pictureboxes[i] = new PictureBox();
}
这是我到目前为止所做的:
MySqlConnection conn = new MySqlConnection(connStr);
try
{
conn.Open();
string sql = "SELECT image FROM drinks";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
for (int i = 0; i < anzahl; i++)
{
pictureboxes[i].Location = new System.Drawing.Point(80 + i * 100, 40);
pictureboxes[i].Name = "pictureBox" + i;
pictureboxes[i].SizeMode = PictureBoxSizeMode.Zoom;
pictureboxes[i].Size = new System.Drawing.Size(300, 300);
pictureboxes[i].Image = ByteArrayToImage((byte[])(rdr.GetValue(0)));
panel1.Controls.Add(pictureboxes[i]);
//rdr.NextResult();
}
}
rdr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
conn.Close();
ByteArrayToImage 函数:
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
当我将rdr.GetValue(0) 更改为rdr.GetValue(i) 时,索引超出范围。
我必须如何更改代码才能输出表格中的所有图像?
【问题讨论】:
-
在谷歌上搜索如何在调用
command.ExecuteReader()方法时使用while 循环,你不使用if (rdr.Read()),网上有很多工作示例。 -
将 if (rdr.Read()) 更改为 while (rdr.Read())
-
pictureboxes[i].Image = ByteArrayToImage((byte[])(rdr.GetValue(0)))这应该使用列名而不是序号位置pictureboxes[i].Image = ByteArrayToImage((byte[])(rdr.["YourColumn"])访问,并在必要时进行适当的转换。