2013-07-06 37 views
1

我想從SQL表中檢索圖像並將其保存在列表中,並在我的列表視圖中顯示它。但我不知道該怎麼做。我需要你的幫助。使用數據庫中的圖像填充列表

我正在使用SQL Server 2008,Visual Studio 2008,C#窗口應用程序。

這裏是我的代碼:

cmd = new SqlCommand("Select ScanImage from ScanDocuments", con); 
dr = cmd.ExecuteReader(); 

List<ImageList> lstitem = new List<ImageList>(); 

while (dr.Read()) 
{ 
    ImageList _image = new ImageList(); 
    byte[] data = (byte[])dr["ScanImage"]; 

    MemoryStream ms = new MemoryStream(data); 
    Image bmp = new Bitmap(ms); 

    lstitem.Add(bmp); 
} 
+2

向我們展示您自己的一些努力!你試過什麼了?你卡在哪裏?你遇到的問題是什麼? –

+0

請看我編輯的問題。我在lstitem.add(bmp)出錯。 –

回答

1

你的代碼中有幾個缺陷 - 你需要使用這樣的事情,而不是:

// define connection string and select statement 
// I used AdventureWorks 2012 database - change to match *YOUR* environment 
string connectionString = "server=.;database=AdventureWorks2012;integrated security=SSPI;"; 
string query = "SELECT ThumbNailPhoto FROM Production.ProductPhoto"; 

// define a list of "Image" objects 
List<Image> listOfImages = new List<Image>(); 

// using the SqlConnection and SqlCommand .... 
using(SqlConnection conn = new SqlConnection(connectionString)) 
using (SqlCommand selectCmd = new SqlCommand(query, conn)) 
{ 
    // open connection 
    conn.Open(); 

    // execute SqlCommand to return a SqlDataReader 
    using (SqlDataReader rdr = selectCmd.ExecuteReader()) 
    { 
     // iterate over the reader 
     while (rdr.Read()) 
     { 
       // load the bytes from the database that represent your image 
       var imageBytes = (byte[]) rdr[0]; 

       // put those bytes into a memory stream and "rewind" the memory stream 
       MemoryStream memStm = new MemoryStream(imageBytes); 
       memStm.Seek(0, SeekOrigin.Begin); 

       // create an "Image" from that memory stream 
       Image image = Image.FromStream(memStm); 

       // add image to list 
       listOfImages.Add(image); 
     } 
    } 

    conn.Close(); 
} 

這對我的作品就好了 - 它裝載101 ThumbNailPhoto來自AdventureWorks2012數據庫