2013-03-13 101 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); 
相關問題