首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用数据库中的图像填充列表

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

Stack Overflow用户
提问于 2013-07-06 19:00:45
回答 1查看 3.5K关注 0票数 1

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

我使用的是SQL Server2008,Visual Studio2008,C#窗口应用程序。

下面是我的代码:

代码语言:javascript
运行
复制
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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-07 05:02:35

您的代码有几个缺陷-您需要使用下面这样的代码:

代码语言:javascript
运行
复制
// 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();
}

这对我来说工作得很好-它从AdventureWorks2012数据库加载101个ThumbNailPhoto

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17502292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档