简体   繁体   中英

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.

In the database the image is stored as byte[] so I want to put it in data table and display it in a 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?

Here is an MSDN article on using a DataGridViewImageColumn

http://msdn.microsoft.com/en-us/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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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