简体   繁体   English

从SQL用C#在DataGridView中显示图像

[英]Display an image in DataGridView in C# from SQL

I want to display an image in a DataGridView in a Windows Forms application from a SQL Server database. 我想从SQL Server数据库的Windows Forms应用程序的DataGridView中显示图像。

In the database the image is stored as byte[] so I want to put it in data table and display it in a DataGridView : 在数据库中,图像以byte[]形式存储,因此我想将其放在数据表中并在DataGridView显示:

SqlCommand com = new SqlCommand("select PKID,Names,Position,picture  from Delegation where PKID='" + id + "'", con);
DataTable dt = new DataTable();
SqlDataAdapter dr = new SqlDataAdapter(com);

dr.Fill(dt);
datagrideview1.datasource = dt;

So in the DataGridView it displays ID,name,position but the picture is not displayed, so what do I do? 因此,在DataGridView它显示ID,name,position但未显示图片,那么该怎么办?

Here is an MSDN article on using a DataGridViewImageColumn 这是有关使用DataGridViewImageColumn的MSDN文章

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewimagecolumn(v=vs.110).aspx http://msdn.microsoft.com/zh-CN/library/system.windows.forms.datagridviewimagecolumn(v=vs.110).aspx

Code sample is pretty huge so I've refrained from posting it in its entirety, here a good representative sample I think: 代码示例非常庞大,因此我避免将其完整发布,在此我认为是一个很好的代表性示例:

 private void CreateColumns()
    {
        DataGridViewImageColumn imageColumn;
        int columnCount = 0;
        do
        {
            Bitmap unMarked = blank;
            imageColumn = new DataGridViewImageColumn();

            //Add twice the padding for the left and  
            //right sides of the cell.
            imageColumn.Width = x.Width + 2 * bitmapPadding + 1;

            imageColumn.Image = unMarked;
            dataGridView1.Columns.Add(imageColumn);
            columnCount = columnCount + 1;
        }
        while (columnCount < 3);
    }

Essentially you create an image column and then just bind the appropriate data to it. 本质上,您创建一个图像列,然后将适当的数据绑定到该列。 In this case it would be a bitmap. 在这种情况下,它将是位图。

Getting data from database is straightforward. 从数据库获取数据非常简单。 Real challange here is to setup datagridview so it can show image. 这里真正的挑战是设置datagridview以便它可以显示图像。

You will have to add a column which can show images. 您将必须添加一列以显示图像。 Have a look at this answer . 看看这个答案 It will help you to get the desired output. 这将帮助您获得所需的输出。

There is an image column type for the DataGridView , the DataGridViewImageColumn , which has an image property that you can pass a bitmap to. DataGridView有一个image列类型, DataGridViewImageColumn ,它具有图像属性,您可以将位图传递给该图像属性。

我发现答案可能是数据Gride View未显示图像,因为我的数据库有问题,所以我清除了所有列,并且可以正常工作,并且秘密地​​在数据网格视图中查看任何图像首先将图像转换为byte []并将其插入之后从数据库中的数据库中调用byte []的数据库,它就可以工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM