Solved

Displaying images in datagrid - Windows Forms (VB.Net)

Posted on 2003-12-08
8
1,445 Views
Last Modified: 2012-08-13
A datagrid on a Windows Forms displays the rows from a single table. One of the columns in the table contains the full path of images. When displaying the rows, I want to display the image, rather the full path, in the datagrid. How do I do this?

Essentially, what I am trying to ask is, 'How do we host image controls, in a datagrid'. I am looking for VB.Net assistance and not C#. Also, I have seen code that does this in Web Forms (ASP.Net) using TemplateColumns. And that is not what I am looking at either.

thanks. Help appreciated.

--.Net Newbie
0
Comment
Question by:Keyboard
  • 3
  • 3
  • 2
8 Comments
 
LVL 6

Assisted Solution

by:pillbug22
pillbug22 earned 125 total points
ID: 9898492
5.81 How can I have a column of bitmaps in a DataGrid
http://www.syncfusion.com/faq/winforms/search/1019.asp


From a really good Windows Forms (.NET) FAQ site (VB & C#)
http://www.syncfusion.com/FAQ/winforms/default.asp
0
 
LVL 15

Accepted Solution

by:
Raisor earned 125 total points
ID: 9898639
Hi,

Here's an example -> without any modifications yet -> if you can not customize it then just ask -> I'll be able to explain is I've written this on my own -> it's an image catalogue for an e-card service -> all pictures are stored in a sql server database -> you'll see here -> ascx / ascx.vb and the DBclass:



<%@ Control Language="vb" AutoEventWireup="false" Codebehind="Catalogue1.ascx.vb" Inherits="GermanGateway.Catalogue1" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<table>
      <tr>
            <td vAlign="top" align="middle" width="30%" height="*">
                  <P><asp:datalist id="DataList1" repeatdirection="Horizontal" BorderColor="#660033" BorderWidth="0px" CellSpacing="21" CellPadding="0" Font-Name="Verdana" FooterStyle-ForeColor="#ffff33" ShowHeader="False" Font-Size="8pt" Font-Names="Verdana" runat="server">
                              <SelectedItemStyle BorderColor="#C00000"></SelectedItemStyle>
                              <ItemTemplate>
                                    <asp:imagebutton OnClick="StartTest" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ImageID") %>' id=ImageSelection ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "ImageID")) %>' AlternateText="<%# SetAltText %>" Runat="server" Width="100">
                                    </asp:imagebutton>
                                    <CENTER>
                                          <P>
                                                <asp:label id=lbl1 Font-Size="8pt" ForeColor="#660000" Runat="server" Font-Bold="true" text='<%# DataBinder.Eval(Container.DataItem, "ImageText") %>'>
                                                </asp:label></P>
                                          <P>
                                                <asp:label id=Label20 Font-Size="8pt" ForeColor="#660000" Runat="server" Font-Bold="true" text='<%# DataBinder.Eval(Container.DataItem, "ImageWidth") &amp; "x" &amp; DataBinder.Eval(Container.DataItem, "ImageHeigth") %>'>
                                                </asp:label></P>
                                    </CENTER>
                              </ItemTemplate>
                              <FooterStyle ForeColor="#FFFF33" Width="125px"></FooterStyle>
                              <HeaderStyle BackColor="#AAAADD"></HeaderStyle>
                        </asp:datalist></P>
                  <FONT face="verdana" color="#ffff33" size="3"><STRONG>
                              <P align="center"><asp:imagebutton id="lnkFirst" onclick="PagerButton2Click" Font-Name="Verdana" Font-Size="12pt" runat="server" CommandArgument="0" ForeColor="#ffff33" ImageUrl="\e-cards\images\bw_first.gif" Visible="False"></asp:imagebutton>&nbsp;&nbsp;&nbsp;
                                    <asp:imagebutton id="lnkPrev" onclick="PagerButton2Click" Font-Name="Verdana" Font-Size="12pt" runat="server" CommandArgument="prev" ForeColor="#ffff33" ImageUrl="\e-cards\images\bw_prev.gif" Visible="False"></asp:imagebutton>&nbsp;&nbsp;&nbsp;
                                    <asp:imagebutton id="lnkNext" onclick="PagerButton2Click" Font-Name="Verdana" Font-Size="12pt" runat="server" CommandArgument="next" ForeColor="#ffff33" ImageUrl="\e-cards\images\bw_next.gif" Visible="False"></asp:imagebutton>&nbsp;&nbsp;&nbsp;
                                    <asp:imagebutton id="lnkLast" onclick="PagerButton2Click" Font-Name="Verdana" Font-Size="12pt" runat="server" CommandArgument="last" ForeColor="#ffff33" ImageUrl="\e-cards\images\bw_last.gif" Visible="False"></asp:imagebutton></P>
                        </STRONG></FONT>
            </td>
      </tr>
</table>
<table width="100%" align="right">
      <tr>
            <td align="left" width="76%">
                  <P align="center"><asp:label id="lblStatus" Font-Name="verdana" Font-Size="10pt" Runat="server"></asp:label></P>
                  <P align="center">
                        <asp:label id="intCurrIndex" Runat="server" Visible="False"></asp:label><asp:label id="intPageSize" Runat="server" Visible="False"></asp:label><asp:label id="intRecordCount" Runat="server" Visible="False"></asp:label></P>
            </td>
      </tr>
</table>


Public MustInherit Class Catalogue1
    Inherits System.Web.UI.UserControl
      Protected WithEvents lnkFirst As System.Web.UI.WebControls.ImageButton
      Protected WithEvents lnkPrev As System.Web.UI.WebControls.ImageButton
      Protected WithEvents lnkNext As System.Web.UI.WebControls.ImageButton
      Protected WithEvents lnkLast As System.Web.UI.WebControls.ImageButton
      Protected WithEvents ImageSelection As System.Web.UI.WebControls.ImageButton
      Public Shared theImage As String
      Public Shared myCardID As Long
      Private theLang As String
      Public picCount As Long
      Protected WithEvents DataList1 As System.Web.UI.WebControls.DataList
      Public Shared WithEvents lblStatus As System.Web.UI.WebControls.Label
      Public Shared WithEvents intCurrIndex As System.Web.UI.WebControls.Label
      Public Shared WithEvents intPageSize As System.Web.UI.WebControls.Label
      Public Shared WithEvents intRecordCount As System.Web.UI.WebControls.Label
      Public userLang As Integer
      Public Shared catCount As Long

#Region " Vom Web Form Designer generierter Code "

      'Dieser Aufruf ist für den Web Form-Designer erforderlich.
      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

      End Sub

      Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: Diese Methode ist für den Web Form-Designer erforderlich
            'Verwenden Sie nicht den Code-Editor zur Bearbeitung.
            InitializeComponent()
      End Sub

#End Region

      Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            If Not Page.IsPostBack() Then
                  intPageSize.Text = "5"
                  intCurrIndex.Text = "0"
                  DataBind()
            End If
            If Not Page.IsPostBack Then
                  DataList1.DataBind()
            End If
            BindGrid(1)
      End Sub

      Private Sub PrintStatus()
            lblStatus.Text = "Total Records:<b>" & intRecordCount.Text
            lblStatus.Text += "</b>"
            If catCount > 5 Then
                  lblStatus.Text += " - Showing Page:<b> "
                  lblStatus.Text += CStr(CInt(CInt(intCurrIndex.Text) / CInt(intPageSize.Text) + 1))
                  lblStatus.Text += "</b> of <b>"
                  If (CInt(intRecordCount.Text) Mod CInt(intPageSize.Text)) > 0 Then
                        lblStatus.Text += CStr(CInt(CInt(intRecordCount.Text) / CInt(intPageSize.Text) + 1))
                  Else
                        lblStatus.Text += CStr(CInt(intRecordCount.Text) / CInt(intPageSize.Text))
                  End If
                  lblStatus.Text += "</b>"
            End If
      End Sub

      Public Sub BindGrid(ByVal theID As Long)
            Dim dPage As GermanGateway.c_default
            Dim ImageCatalogue As GermanGateway.PictureDB = New GermanGateway.PictureDB()
            DataList1.DataSource = ImageCatalogue.GetDataSource(CInt(dPage.langID), theID)
            DataList1.DataBind()
            intRecordCount.Text = catCount
            ImageCatalogue = Nothing
            If catCount > 5 Then
                  lnkFirst.Visible = True
                  lnkPrev.Visible = True
                  lnkNext.Visible = True
                  lnkLast.Visible = True
            Else
                  lnkFirst.Visible = False
                  lnkPrev.Visible = False
                  lnkNext.Visible = False
                  lnkLast.Visible = False
            End If
            dPage = Nothing
            PrintStatus()
      End Sub

      Sub StartTest(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
            Dim arg As String = CType(sender, ImageButton).CommandArgument
            Dim mPage As GermanGateway.c_default
            mPage.userImageChoice = CLng(arg)
            mPage.userImageCategory = 1
            'CType(sender, ImageButton).BorderStyle = BorderStyle.Inset
            mPage.Catalogues1.Visible = False
            mPage.SelectMenu1.Visible = True
            mPage.SelectMenu1.Dispose()
            mPage = Nothing
            arg = Nothing
      End Sub

      Sub PagerButton2Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
            Dim arg As String = CType(sender, ImageButton).CommandArgument
            Select Case arg
                  Case "next"
                        If CInt(intCurrIndex.Text) + 1 < CInt(intRecordCount.Text) Then
                              intCurrIndex.Text = CStr(CInt(intCurrIndex.Text) + CInt(intPageSize.Text))
                        End If
                        DataBind()
                  Case "prev"
                        intCurrIndex.Text = CStr(CInt(intCurrIndex.Text) - CInt(intPageSize.Text))
                        If CInt(intCurrIndex.Text) < 0 Then
                              intCurrIndex.Text = "0"
                        End If
                        DataBind()
                  Case "last"
                        Dim tmpInt As Integer

                        tmpInt = CInt(intRecordCount.Text) Mod CInt(intPageSize.Text)
                        If tmpInt > 0 Then
                              intCurrIndex.Text = CStr(CInt(intRecordCount.Text) - tmpInt)
                        Else
                              intCurrIndex.Text = CStr(CInt(intRecordCount.Text) - CInt(intPageSize.Text))
                        End If
                        DataBind()
                  Case Else
                        intCurrIndex.Text = "0"
                        DataBind()
            End Select
            BindGrid(1)
      End Sub

      Public Function SetAltText() As String
            Dim lngSet As GermanGateway.LangSetDB = New GermanGateway.LangSetDB()
            Dim myPageText As GermanGateway.PageData
            myPageText = lngSet.GetPageData(CInt(userLang), "infImageUsed", 0, 0)
            Return myPageText.pageMessage
      End Function

      Public Shared Function AddIDToURL(ByVal theURL As String, ByVal theID As Long) As String
            Return (theURL & "&c=" & CStr(theID))
      End Function

      Function FormatURL(ByVal strArgument) As String
            Dim mPage As GermanGateway.MainMenu
            mPage.URLBuffer = ConfigurationSettings.AppSettings("TheECard") & "/ImgCtrl/getimg.aspx?id=" & strArgument
            mPage = Nothing
            Return ("../ImgCtrl/getimg.aspx?id=" & strArgument)
      End Function

      Private Sub DataList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataList1.SelectedIndexChanged
            DataList1.DataBind()

      End Sub

End Class


PS: Don't care about "GermanGateway.LangSetDB" <--- it only takes care that all this can be dispayed in 10 languages ... the important for you is "GermanGateway.PictureDB" ---> and this is here:


Imports System
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing

Namespace GermanGateway

      Public Class PictureDB

            Public Function GetCategories(ByVal langID As Integer) As SqlDataReader
                  Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("connectionString3"))
                  Dim myCommand As New SqlCommand("GetImagesCategories", myConnection)
                  myCommand.CommandType = CommandType.StoredProcedure
                  Dim parameterLanguageID As SqlParameter = New SqlParameter("@langID", SqlDbType.Int, 4)
                  parameterLanguageID.Value = langID
                  myCommand.Parameters.Add(parameterLanguageID)
                  myConnection.Open()
                  Dim dr As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
                  myConnection = Nothing
                  Return dr
            End Function

            Public Function GetColors(ByVal langID As Integer) As SqlDataReader
                  Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("connectionString5"))
                  Dim myCommand As New SqlCommand("GetColors", myConnection)
                  myCommand.CommandType = CommandType.StoredProcedure
                  Dim parameterLanguageID As SqlParameter = New SqlParameter("@languageID", SqlDbType.Int, 4)
                  parameterLanguageID.Value = langID
                  myCommand.Parameters.Add(parameterLanguageID)
                  myConnection.Open()
                  Dim dr As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
                  myConnection = Nothing
                  Return dr
            End Function

            Public Function GetAlignments(ByVal langID As Integer) As SqlDataReader
                  Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("connectionString5"))
                  Dim myCommand As New SqlCommand("GetAlignments", myConnection)
                  myCommand.CommandType = CommandType.StoredProcedure
                  Dim parameterLanguageID As SqlParameter = New SqlParameter("@languageID", SqlDbType.Int, 4)
                  parameterLanguageID.Value = langID
                  myCommand.Parameters.Add(parameterLanguageID)
                  myConnection.Open()
                  Dim dr As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
                  myConnection = Nothing
                  Return dr
            End Function

            Public Function GetLanguages(ByVal langID As Integer) As SqlDataReader
                  Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("connectionString5"))
                  Dim myCommand As New SqlCommand("GetLanguageSet", myConnection)
                  myCommand.CommandType = CommandType.StoredProcedure
                  Dim parameterLanguageID As SqlParameter = New SqlParameter("@languageID", SqlDbType.Int, 4)
                  parameterLanguageID.Value = langID
                  myCommand.Parameters.Add(parameterLanguageID)
                  myConnection.Open()
                  Dim dr As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
                  myConnection = Nothing
                  Return dr
            End Function

            Public Function BindGrid(ByVal theID As Long) As SqlDataReader
                  ' Create Instance of Connection and Command Object
                  Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString2"))
                  Dim myCommand As SqlCommand = New SqlCommand("sp_UserPicsTest", myConnection)
                  myCommand.CommandType = CommandType.StoredProcedure
                  Dim parameterUserID As SqlParameter = New SqlParameter("@userID", SqlDbType.Int, 4)
                  parameterUserID.Value = theID
                  myCommand.Parameters.Add(parameterUserID)
                  myConnection.Open()
                  Dim result As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
                  myConnection = Nothing
                  Return result
            End Function

            Public Function GetDataSource(ByVal langID As Long, ByVal catID As Long) As System.Collections.ICollection
                  Dim DS As DataSet
                  'Dim MyConnection As SqlConnection
                  Dim MyCommand As SqlDataAdapter
                  'MyConnection = New SqlConnection("Data Source=localhost;Initial Catalog=Northwind;" & "Integrated Security=True")
                  'MyCommand = New SqlDataAdapter("SELECT CustomerID" & " FROM Customers", MyConnection)
                  Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString3"))
                  MyCommand = New SqlDataAdapter("Exec GetImagesFromCategories " & catID & "," & langID, myConnection)
                  DS = New DataSet()
                  Select Case catID
                        Case 1
                              MyCommand.Fill(DS, "Customers")
                              Dim cPage As Catalogue1
                              cPage.catCount = CStr(DS.Tables(0).Rows.Count)
                              cPage = Nothing
                              DS = Nothing
                              DS = New DataSet()
                              MyCommand.Fill(DS, CInt(cPage.intCurrIndex.Text), CInt(cPage.intPageSize.Text), "Customers")
                        Case 2
                              MyCommand.Fill(DS, "Customers")
                              Dim cPage As Catalogue2
                              cPage.catCount = CStr(DS.Tables(0).Rows.Count)
                              cPage = Nothing
                              'DS = Nothing
                              'DS = New DataSet()
                              'MyCommand.Fill(DS, CInt(cPage.intCurrIndex.Text), CInt(cPage.intPageSize.Text), "Sales")

                        Case Else
                  End Select
                  myConnection.Close()
                  myConnection = Nothing
                  Return DS.Tables("Customers").DefaultView
            End Function              ' GetDataSource

      End Class

End Namespace



As I've said before -> I'll be here for special questions!

Best regards, Raisor
0
 

Author Comment

by:Keyboard
ID: 9898803
pillbug22: That was a good example. Alas, the author uses an arraylist to store all the images. I don't want to store the images in a separate collection.

Raisor:
Uh...it looks like ASP.net. I don't have the expertise to convert the code to VB.Net (Windows Forms) yet. Well, can you give the Windows Forms code?

So guys, help me out....
0
 
LVL 6

Expert Comment

by:pillbug22
ID: 9898852
I haven't looked at his code, but I don't see why you couldn't use the images from your own collection instead of an array.

Arrays, datasets, datareaders, XML, they all hold the same thing, just in different ways.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 15

Expert Comment

by:Raisor
ID: 9899020
Hi,

@keyboard ... ups!!! ... You're right ... my mistake!!!

@pillbug22 ... do you have to provide a solution that fits with keyboards' request ... or shall I take care?


Best regards, Raisor

0
 
LVL 6

Expert Comment

by:pillbug22
ID: 9899107
Well, the example I gave used an Array to store the images (which he didn't want), so I'm working through the code to use the returned SQL row instead.  Be my guest to help out here!

Here's the important stuff I believe:





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

        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)
            dt.Rows.Add(dr)
        Next

        'store bitmaps in an arraylist
        bitMaps = New ArrayList()
        Dim strm As System.IO.Stream = [GetType]().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Blue hills.jpg")
        bitMaps.Add(New Bitmap(strm))
        strm = [GetType]().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Sunset.jpg")
        bitMaps.Add(New Bitmap(strm))
        strm = [GetType]().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Water lilies.jpg")
        bitMaps.Add(New Bitmap(strm))
        strm = [GetType]().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Winter.jpg")
        bitMaps.Add(New Bitmap(strm))


        'create an imagelist
        '                  ImageList images = new ImageList();
        '                  System.IO.Stream strm = GetType().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Blue hills.jpg");
        '                  images.Images.Add(new Bitmap(strm));
        '                  strm = GetType().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Sunset.jpg");
        '                  images.Images.Add(new Bitmap(strm));
        '                  strm = GetType().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Water lilies.jpg");
        '                  images.Images.Add(new Bitmap(strm));
        '                  strm = GetType().Assembly.GetManifestResourceStream("ImageCellInDataGrid.Winter.jpg");
        '                  images.Images.Add(new Bitmap(strm));
        '                  
        '                  images.Images.Add(SystemIcons.Warning.ToBitmap());
        '                  images.Images.Add(SystemIcons.Application.ToBitmap());
        '                  images.Images.Add(SystemIcons.Asterisk.ToBitmap());
        '                  images.Images.Add(SystemIcons.Error.ToBitmap());
        '                  images.Images.Add(SystemIcons.Exclamation.ToBitmap());
        '                  images.Images.Add(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
        tableStyle.GridColumnStyles.Add(tbc)

        Dim width As Integer = Me.dataGrid1.ClientSize.Width - tbc.Width - Me.dataGrid1.RowHeaderWidth - 4
        Dim tbc1 As New DataGridImageCell()
        tbc1.MappingName = "Images"
        tbc1.HeaderText = "Images"
        tbc1.theImages = bitMaps
        tbc1.Width = width
        tableStyle.GridColumnStyles.Add(tbc1)

        Me.dataGrid1.TableStyles.Add(tableStyle)
        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 'Form1_Load









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 'New
   
   
   Public Property theImages() As ArrayList
      Get
         Return theImages1
      End Get
      Set
         theImages1 = value
      End Set
   End Property
   
    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)
                        Else
                            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 'Paint


    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 'Edit



    Public Enum GridImageCellDrawOption
        FitToCell = 0
        NoResize = 1
        FitProportionally = 2
    End Enum 'GridImageCellDrawOption

End Class 'DataGridImageCell
0
 
LVL 15

Expert Comment

by:Raisor
ID: 9899326
Hi,

@pillbug22 ... After looking at your code I'm not having any problem to state that I'm sure your example is a very good one!!!

@keyboaord ... I was looking a little arround in old and current projects ---> "my source code collection ;-))" <--- and unforunately I've found only an "Amazon Appplication" -> that app is working with amazon product catalogues and with my personal developer token from amazon -> on any query the results are presented in a datagrid ... with images of products -> but!!! ... to extract the important source code would be more work than starting a small app from the scratch ... as you've stated you're newbie to vb.net and that's why I think that this article here can fit perfectly to your needs ---> http://www.vbdotnetheaven.com/Code/Jun2003/2078.asp <--- It will show you a lot of how to work with a datagrid in vb.net and it will give you an everlasting experience in working/programming with all possible controls that can be used in a datagrid (even generated from a database!) ...


Best regards, Raisor
0
 

Author Comment

by:Keyboard
ID: 9900039
thanks pilbug22 and raisor for your continued support.

pilbug22: the image is actually painted in the paint methods. though been working with VB6 for ages, never even once, did I need to use the paint, draw, graphics...so that side of the programming world is new to me. essentially the image needs to be drawn in the grid cell, right? the code uses the array, i will attempt to decipher the code. but can we do something the way I want....
....read a sql table, get a bunch of rows in a dataset...use this dataset to bind the datagrid. when the rows are being loaded, load the image from the file path......
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

708 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

19 Experts available now in Live!

Get 1:1 Help Now