How to display images in datagrid cells

Posted on 2006-04-18
Last Modified: 2008-01-09
Hi experts,

I'm just looking for a way to display JPEG images in datagrid cells.
The datagrid has two columns, the first one is the name of the image and the second column would be the actural image. All images is on local machine, say "C:\temp\image01.jpg"....
I'm using 2003

Thanks for your help.
Question by:snow_moon
    LVL 27

    Accepted Solution

    Hi snow_moon,
    Here is a sample that I had.....

    'FORM 1

    Imports System
    Imports System.Drawing
    Imports System.Collections
    Imports System.ComponentModel
    Imports System.Windows.Forms
    Imports System.Data
    Public Class Form1
        Inherits System.Windows.Forms.Form
        Private topPos As Integer
        Private nRows As Integer = 5
        Private bitMaps As ArrayList
        Private WithEvents dataGrid1 As System.Windows.Forms.DataGrid
    #Region "Windows Form Designer generated code"
        Public Sub New()
            ' Required for Windows Form Designer support
        End Sub 'New
        ' TODO: Add any constructor code after InitializeComponent call
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                End If
            End If
        End Sub 'Dispose

        '/ <summary>
        '/ Required method for Designer support - do not modify
        '/ the contents of this method with the code editor.
        '/ </summary>
        Friend WithEvents ImageList1 As System.Windows.Forms.ImageList
        Private components As System.ComponentModel.IContainer
        Private Sub InitializeComponent()
            Me.components = New System.ComponentModel.Container
            Me.dataGrid1 = New System.Windows.Forms.DataGrid
            Me.ImageList1 = New System.Windows.Forms.ImageList(Me.components)
            CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
            Me.dataGrid1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                        Or System.Windows.Forms.AnchorStyles.Left) _
                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.dataGrid1.DataMember = ""
            Me.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
            Me.dataGrid1.Location = New System.Drawing.Point(20, 12)
            Me.dataGrid1.Name = "dataGrid1"
            Me.dataGrid1.Size = New System.Drawing.Size(408, 188)
            Me.dataGrid1.TabIndex = 0
            Me.ImageList1.ImageSize = New System.Drawing.Size(16, 16)
            Me.ImageList1.TransparentColor = System.Drawing.Color.Transparent
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(440, 209)
            Me.Name = "Form1"
            Me.Text = "Form1"
            CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).EndInit()

        End Sub 'InitializeComponent
    #End Region
        '/ <summary>
        '/ The main entry point for the application.
        '/ </summary>
        <STAThread()> _
        Shared Sub Main()
            Application.Run(New Form1)
        End Sub
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'create a datatable
            Dim dt As New DataTable("MyTable")

            dt.Columns.Add(New DataColumn("Col0"))
            dt.Columns.Add(New DataColumn("Images", GetType(Integer)))
            dt.Columns.Add(New DataColumn("Col2"))

            Dim r As New Random
            Dim i As Integer

            For i = 0 To nRows - 1
                Dim dr As DataRow = dt.NewRow()
                dr(0) = String.Format("row{0}", i)
                dr(1) = r.Next(4)
                dr(2) = r.Next(4)

            ' You can use Build Actioin = Embedded Resource to stroe jpegs for your datagrid
            'store bitmaps in an arraylist
            bitMaps = New ArrayList
            Dim executing_assembly As System.Reflection.Assembly = Me.GetType.Assembly.GetEntryAssembly()
            ' Get the namespace.

            'Dim my_namespace As String = executing_assembly.GetName().Name.ToString()
            'Dim strm As System.IO.Stream
            'strm = [GetType]().Assembly.GetManifestResourceStream(my_namespace & ".Blue hills.jpg")
            'bitMaps.Add(New Bitmap(strm))
            'strm = [GetType]().Assembly.GetManifestResourceStream(my_namespace & ".Sunset.jpg")
            'bitMaps.Add(New Bitmap(strm))
            'strm = [GetType]().Assembly.GetManifestResourceStream(my_namespace & ".Water lilies.jpg")
            'bitMaps.Add(New Bitmap(strm))
            'strm = [GetType]().Assembly.GetManifestResourceStream(my_namespace & ".Winter.jpg")
            'bitMaps.Add(New Bitmap(strm))
            'strm = [GetType]().Assembly.GetManifestResourceStream(my_namespace & ".DirtRoad.jpg")
            'bitMaps.Add(New Bitmap(strm))

            'OR Use this
            bitMaps.Add(New Bitmap(SystemIcons.Warning.ToBitmap()))
            bitMaps.Add(New Bitmap(SystemIcons.Application.ToBitmap()))
            bitMaps.Add(New Bitmap(SystemIcons.Asterisk.ToBitmap()))
            bitMaps.Add(New Bitmap(SystemIcons.Error.ToBitmap()))
            bitMaps.Add(New Bitmap(SystemIcons.Exclamation.ToBitmap()))
            bitMaps.Add(New Bitmap(SystemIcons.Hand.ToBitmap()))

            Dim tableStyle As New DataGridTableStyle
            tableStyle.MappingName = "MyTable"
            Dim tbc As New DataGridTextBoxColumn
            tbc.MappingName = "Col0"
            tbc.HeaderText = "Column 1"
            tbc.Width = 50

            Dim width As Integer
            width = 50
            'OR use
            'width = Me.dataGrid1.ClientSize.Width - tbc.Width - Me.dataGrid1.RowHeaderWidth - 4
            Dim tbc1 As New DataGridImageCell
            tbc1.MappingName = "Images"
            tbc1.HeaderText = "Images"
            Dim h As ImageList.ImageCollection
            tbc1.theImages = bitMaps
            tbc1.Width = width

            width = 50
            Dim tbc2 As New DataGridImageCell
            tbc2.MappingName = "Col2"
            tbc2.HeaderText = "Column 2"
            '  Dim h As ImageList.ImageCollection
            tbc2.theImages = bitMaps
            tbc2.Width = width

            Me.dataGrid1.DataSource = dt
            dt.DefaultView.AllowNew = False

            Dim rect As Rectangle = Me.dataGrid1.GetCellBounds(0, 0)
            topPos = rect.Top
            Dim height As Integer = (Me.dataGrid1.ClientSize.Height - topPos - nRows) / nRows
            tableStyle.PreferredRowHeight = height
            Me.dataGrid1.DataSource = Nothing
            Me.dataGrid1.DataSource = dt
        End Sub
        Private Sub dataGrid1_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dataGrid1.SizeChanged
            Dim height As Integer = (Me.dataGrid1.ClientSize.Height - topPos - nRows) / nRows
            Dim tableStyle As DataGridTableStyle = Me.dataGrid1.TableStyles("MyTable")

            If Not tableStyle Is Nothing Then
                Dim width As Integer = Me.dataGrid1.ClientSize.Width - tableStyle.GridColumnStyles("Col0").Width - Me.dataGrid1.RowHeaderWidth - 4

                tableStyle.GridColumnStyles("Images").Width = width
                tableStyle.GridColumnStyles("Col2").Width = width

                tableStyle.PreferredRowHeight = height
                Dim o As Object = Me.dataGrid1.DataSource
                Me.dataGrid1.DataSource = Nothing
                Me.dataGrid1.DataSource = o
            End If
        End Sub
    End Class


    Imports System
    Imports System.Windows.Forms
    Imports System.Drawing
    Imports System.Data
    Imports System.Collections
    '/ <summary>
    '/ Summary description for DataGridImageCell.
    '/ </summary>
    Public Class DataGridImageCell
        Inherits DataGridTextBoxColumn
        Private theImages1 As ArrayList
        Public Sub New()
        End Sub
        Public Property theImages() As ArrayList
                Return theImages1
            End Get
            Set(ByVal Value As ArrayList)
                theImages1 = Value
            End Set
        End Property
        Protected Overloads Overrides Sub Edit(ByVal [source] As System.Windows.Forms.CurrencyManager, ByVal rowNum As Integer, ByVal bounds As System.Drawing.Rectangle, ByVal [readOnly] As Boolean, ByVal instantText As String, ByVal cellIsVisible As Boolean)
            'overriden to avoid editing
        End Sub
        Public Enum GridImageCellDrawOption
            FitToCell = 0
            NoResize = 1
            FitProportionally = 2
        End Enum
        Protected Overloads Overrides Sub Paint(ByVal g As System.Drawing.Graphics, ByVal bounds As System.Drawing.Rectangle, ByVal [source] As System.Windows.Forms.CurrencyManager, ByVal rowNum As Integer, ByVal backBrush As System.Drawing.Brush, ByVal foreBrush As System.Drawing.Brush, ByVal alignToRight As Boolean)
            Dim o As Object = Me.GetColumnValueAtRow([source], rowNum)
            If Not (o Is Nothing) Then
                Dim i As Integer = Fix(o)
                g.FillRectangle(backBrush, bounds)

                Dim bmp As Bitmap = CType(theImages(i), Bitmap)

                'GridImageCellDrawOption cellDrawOption = GridImageCellDrawOption.NoResize;
                'GridImageCellDrawOption cellDrawOption = GridImageCellDrawOption.FitProportionally;
                Dim cellDrawOption As GridImageCellDrawOption = GridImageCellDrawOption.FitToCell

                Dim gu As System.Drawing.GraphicsUnit = System.Drawing.GraphicsUnit.Point

                Dim srcRect As RectangleF = bmp.GetBounds(gu)
                Dim destRect As Rectangle = Rectangle.Empty

                Dim saveRegion As [Region] = g.Clip

                Select Case cellDrawOption
                    Case GridImageCellDrawOption.FitToCell
                        destRect = bounds
                    Case GridImageCellDrawOption.NoResize
                        destRect = New Rectangle(bounds.X, bounds.Y, Fix(srcRect.Width), Fix(srcRect.Height))
                        g.Clip = New [Region](bounds)
                    Case GridImageCellDrawOption.FitProportionally
                        If (True) Then
                            Dim srcRatio As Single = srcRect.Width / srcRect.Height
                            Dim tarRatio As Single = System.Convert.ToSingle(bounds.Width) / bounds.Height
                            destRect = bounds
                            If tarRatio < srcRatio Then
                                destRect.Height = Fix(destRect.Width * srcRatio)
                                destRect.Width = Fix(destRect.Height * srcRatio)
                            End If
                        End If

                    Case Else
                End Select

                If Not destRect.IsEmpty Then
                    'g.DrawImage(bmp, destRect, srcRect, gu)
                    Dim destRectF As New RectangleF(destRect.X, destRect.Y, destRect.Width, destRect.Height)
                    Dim srcRectF As New RectangleF(srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height)

                    g.DrawImage(bmp, destRectF, srcRectF, gu)
                End If
                g.Clip = saveRegion
            End If
        End Sub
    End Class
    LVL 3

    Author Comment

    Thanks planocz ,

    That works perfect!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    It’s quite interesting for me as I worked with Excel using for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
    The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (…
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now