2013-03-13 94 views
0

我有一个winform应用程序(VS 2008),有4个图片框,一个按钮(上传)。我想按照从头到尾的顺序从数据库(sql server 2005)中图片框记录图像,当我点击按钮时。例如:按下按钮,第一个图片框显示第一个图像,按下按钮,第二个图片显示另一个图片框等。然后,第一个图片框显示第五个图像。如何从数据库检索图像到循环中的4个图片框

pb1 = img1, pb2 = img2, pb3 = img3, pb4 = img4, pb1 = img5,..pb4 = img8,pb1 = img9,..etc.. 

所以,出现了一个循环。 我有这段代码,但他只在图片框中记录了一张图片。

private void btnSHow_Click(object sender, EventArgs e) 
{ 
    SqlConnection connect = new SqlConnection("Data Source=JOHNO-PC\\SQLEXPRESS;Initial Catalog=DB_TraficSigns;Integrated Security=True"); 
    SqlCommand command = new SqlCommand("SELECT picture FROM Tab_Sign ORDER BY id", connect); 

    SqlDataAdapter dp = new SqlDataAdapter(command); 
    DataSet ds = new DataSet("Tab_Sign"); 

    byte[] MyData = new byte[0]; 

    dp.Fill(ds, "Tab_Sign"); 
    DataRow myRow; 
    myRow = ds.Tables["Tab_Sign"].Rows[0]; 

    MyData = (byte[])myRow["picture"]; 

    MemoryStream stream = new MemoryStream(MyData); 
    pb1.Image = Image.FromStream(stream); 

} 
+2

对不起,什么是你的问题? – 2013-03-13 17:59:56

+2

不是您的问题的解决方案,但仅供参考:您的'SqlConnection','SqlCommand','SqlDataAdapter'和'MemoryStream'都需要位于'using'块中。 – 2013-03-13 18:13:49

+0

约翰有一个好点。它们都是非托管资源,所以如果你没有妥善处理它们,你可能会遇到内存问题。 – Beska 2013-03-13 18:32:48

回答

1

而不是有pb1,pb2,pb3等,把你的图片框放在一个名为像pictureBoxes的东西。把数组的大小在全球,并使用声明数组时大小(所以它很容易多变,如果你曾经添加或删除pictureboxes。)

int pictureBoxCount = 4; 
int currentPictureBox = 0; 
PictureBox[] pictureBoxes = new PictureBox[pictureBoxCount]; 

然后,每次下载图片时,更新数组索引器。

currentPictureBox = (currentPictureBox + 1) % pictureBoxCount; 

然后,你可以这样做:

pictureBoxes[currentPictureBox].Image = Image.FromStream(stream); 
相关问题