使用数据库中的图像填充列表

时间:2013-07-06 11:00:45

标签: c# sql-server-2008 list listview

我想从SQL表中检索图像并将其保存在列表中并在listview中显示。但我不知道该怎么做。我需要你的帮助。

我使用的是SQL Server 2008,Visual Studio 2008,C#Window Application。

这是我的代码:

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);
}

1 个答案:

答案 0 :(得分: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();
}

这对我来说很合适 - 它从ThumbNailPhoto数据库加载101 AdventureWorks2012