none
how to display more then one Pictures from folder to Listbox and use click in item Listbox to display image in single PictureBox ? RRS feed

  • Question

  • I want :

    1. display names pictures from folder into Listbox .
    2. when click on item name Picture in Listbox to display Picture in PictureBox
    3. I want use all format image

    • Edited by srajmuneer Thursday, May 25, 2017 3:37 PM
    Thursday, May 25, 2017 3:34 PM

Answers

  • Hi

    Slow day here today. Decided to revisit this code.

    Here is a more considered version. Uses an empty Form1 and creates controls at run time. Adds size mode buttons.

    ' blank Form1
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim d As New Dictionary(Of String, String)
        Dim PicTypes As New List(Of String)
        Dim lb As New ListBox
        Dim pb As New PictureBox
        Dim b1, b2, b3, b4, b5 As New Button
        Dim lab As New Label
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

            ' set up allows image types
            ' lower case only
            PicTypes.AddRange({".jpg", ".jpeg", "bmp", ".png"})

            ' set up initial folder path
            FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments


            Size = New Size(600, 500)

            ' set up controls
            With lb
                .Location = New Point(10, 8)
                .Size = New Size(110, 334)
                .Font = New Font(lb.Font.FontFamily, 10)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom
            End With
            With pb
                .Location = New Point(128, 8)
                .Size = New Size(450, 416)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom Or AnchorStyles.Right
                ' set initial PB image size mode
                .SizeMode = PictureBoxSizeMode.Zoom
                SetBC("b3")
            End With
            With lab
                .AutoSize = False
                .TextAlign = ContentAlignment.MiddleLeft
                .Location = New Point(10, 430)
                .Size = New Size(568, 24)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom Or AnchorStyles.Right
            End With
            With b1
                .Text = "Choose Folder"
                .Size = New Size(lb.Width, 26)
                .Location = New Point(10, 334)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b2
                .Text = "Normal"
                .Size = New Size(54, 26)
                .Location = New Point(10, 370)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b3
                .Text = "Zoom"
                .Size = New Size(54, 26)
                .Location = New Point(66, 370)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b4
                .Text = "Stretch"
                .Size = New Size(54, 26)
                .Location = New Point(10, 398)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b5
                .Text = "Center"
                .Size = New Size(54, 26)
                .Location = New Point(66, 398)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With

            ' add controls to Form1
            Controls.AddRange({lb, pb, lab, b1, b2, b3, b4, b5})

            ' create control handlers
            AddHandler lb.SelectedIndexChanged, AddressOf LB_SIC
            AddHandler b1.Click, AddressOf B1_Click
            AddHandler b2.Click, AddressOf B2_Click
            AddHandler b3.Click, AddressOf B3_Click
            AddHandler b4.Click, AddressOf B4_Click
            AddHandler b5.Click, AddressOf B5_Click

        End Sub
        Private Sub LB_SIC(sender As Object, e As EventArgs)
            Dim lb As ListBox = DirectCast(sender, ListBox)
            If lb.SelectedIndex < 0 Then Exit Sub
            Try
                pb.Image = Image.FromFile(lb.SelectedValue.ToString)
                lab.Text = lb.SelectedValue.ToString
            Catch ex As Exception
                MessageBox.Show("ERROR: can't load " & vbCrLf & lb.SelectedValue.ToString)
            End Try
        End Sub
        Private Sub B1_Click(sender As Object, e As EventArgs)
            Dim response As DialogResult = FolderBrowserDialog1.ShowDialog
            If response = DialogResult.OK Then
                lb.DataSource = Nothing
                d.Clear()
                pb.Image = Nothing
                If FolderBrowserDialog1.SelectedPath.Length > 0 Then
                    Dim pictFolder As String = FolderBrowserDialog1.SelectedPath
                    For Each f As String In My.Computer.FileSystem.GetFiles(pictFolder)
                        If PicTypes.Contains(IO.Path.GetExtension(f.ToLower)) Then
                            d.Add(f, IO.Path.GetFileNameWithoutExtension(f))
                        End If
                    Next
                End If
                If d.Count > 0 Then
                    lb.DisplayMember = "value"
                    lb.ValueMember = "key"
                    lb.DataSource = New BindingSource(d, Nothing)
                Else
                    lab.Text = Nothing
                End If
            End If
        End Sub
        Private Sub SetBC(s As String)
            Dim c1 As Color = Color.LightBlue
            Dim c2 As Color = Color.FromKnownColor(KnownColor.Control)

            b2.BackColor = c2
            b3.BackColor = c2
            b4.BackColor = c2
            b5.BackColor = c2

            Select Case s
                Case "b2"
                    b2.BackColor = c1
                Case "b3"
                    b3.BackColor = c1
                Case "b4"
                    b4.BackColor = c1
                Case "b5"
                    b5.BackColor = c1
            End Select
        End Sub
        Private Sub B2_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.Normal
            SetBC("b2")
        End Sub
        Private Sub B3_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.Zoom
            SetBC("b3")
        End Sub
        Private Sub B4_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.StretchImage
            SetBC("b4")
        End Sub
        Private Sub B5_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.CenterImage
            SetBC("b5")
        End Sub
    End Class



    Regards Les, Livingston, Scotland



    • Edited by leshay Friday, May 26, 2017 9:22 PM IronRazerz suggestion
    • Marked as answer by srajmuneer Saturday, May 27, 2017 7:39 PM
    Friday, May 26, 2017 6:27 PM
  •  Here is another quick example.  It requires 1 PictureBox,  1 Button,  and  1 ListBox added to the form.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using fb As New FolderBrowserDialog
                fb.Description = "Select A Folder With Images"
                If fb.ShowDialog = DialogResult.OK Then
                    ListBox1.DataSource = Nothing
                    ListBox1.DataSource = New IO.DirectoryInfo(fb.SelectedPath).GetFiles("*.*").Where(Function(x) ".jpg.jpeg.bmp.gif.png".Contains(IO.Path.GetExtension(x.FullName).ToLower)).ToList
                    ListBox1.DisplayMember = "Name"
                    ListBox1.ValueMember = "FullName"
                End If
            End Using
        End Sub
    
        Private Sub ListBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedValueChanged
            If ListBox1.SelectedValue IsNot Nothing Then PictureBox1.ImageLocation = ListBox1.SelectedValue.ToString
        End Sub
    End Class
    


    If you say it can`t be done then i`ll try it

    • Marked as answer by srajmuneer Saturday, May 27, 2017 7:19 PM
    Friday, May 26, 2017 10:44 PM
  • This one uses a DataGridView.  :)

    Public Class Form6
        Private WithEvents dgv As New DataGridView With {.Parent = Me, .Dock = DockStyle.Right,
            .Width = 300, .RowHeadersVisible = False}
        Private WithEvents OpenButton As New Button With {.Parent = Me,
            .Location = New Point(50, 10), .Text = "Open..."}
        Private Picture1 As New Button With {.Parent = Me}
        Private CurrentFolder As String = "c:\bitmaps\"
    
        Private Sub Form6_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ClientSize = New Size(600, 500)
            Picture1.BackgroundImageLayout = ImageLayout.Zoom
            Form6_Resize(0, Nothing)
            FillDgv(dgv, CurrentFolder)
        End Sub
    
        Private Sub Form6_Resize(sender As Object, e As EventArgs) Handles Me.Resize
            Picture1.Location = New Point(0, OpenButton.Bottom + 10)
            Picture1.Size = New Size(ClientSize.Width - dgv.Width, ClientSize.Height - Picture1.Top)
        End Sub
    
        Private Sub OpenButton_Click(sender As Object, e As EventArgs) Handles OpenButton.Click
            Using dialog As New FolderBrowserDialog()
                dialog.RootFolder = Environment.SpecialFolder.Desktop
                dialog.SelectedPath = CurrentFolder
                dialog.Description = "Select a Folder"
                If dialog.ShowDialog() = DialogResult.OK Then
                    CurrentFolder = dialog.SelectedPath
                    FillDgv(dgv, CurrentFolder)
                End If
            End Using
        End Sub
    
        Private Sub dgv_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellClick
            If e.RowIndex > -1 Then
                'dispose old image
                Dim img As Image = Nothing
                If Picture1.BackgroundImage IsNot Nothing Then img = Picture1.BackgroundImage
    
                Picture1.BackgroundImage = Image.FromFile(dgv.Rows.Item(e.RowIndex).Cells(0).Tag)
                Picture1.Refresh()
    
                If img IsNot Nothing Then img.Dispose()
            End If
        End Sub
    
        Private Sub FillDgv(thisDgv As DataGridView, thisFilePath As String)
            With thisDgv
                .Rows.Clear()
                .Columns.Clear()
                .Columns.Add("FileName", "File Name: ")
    
                Dim img As New DataGridViewImageColumn()
                img.Name = "Image"
                img.Width = 160
                dgv.Columns.Add(img)
    
                'fill the dgv with the files in this folder
                Dim di As New IO.DirectoryInfo(thisFilePath)
                Dim aryFi As IO.FileInfo() = di.GetFiles("*.png")
                Dim fi As IO.FileInfo
    
                For Each fi In aryFi
                    Dim n As Integer = dgv.Rows.Add()
                    .Rows.Item(n).Cells(0).Value = fi.Name
                    .Rows.Item(n).Cells(0).Tag = fi.FullName
                    MakeDGVThumbnail(fi.FullName, dgv, n, 1)
                Next
            End With
        End Sub
    
        Private Sub MakeDGVThumbnail(theFilenamePath As String, dgv As DataGridView, dgvIndex As Integer, dgvColumn As Integer)
            Dim thisBmp As Bitmap = New Bitmap(theFilenamePath)
            Dim w As Integer = thisBmp.Width
            Dim h As Integer = thisBmp.Height
            Dim ratio As Single = CSng(h / w)
    
            w = dgv.Columns(dgvColumn).Width
    
            If ratio > 1 Then
                h = 100
                w = CInt(h / ratio)
            Else
                h = CInt(w * ratio)
            End If
    
            Using bmp As New Bitmap(w, h)
                Using g As Graphics = Graphics.FromImage(bmp)
                    g.DrawImage(thisBmp, 0, 0, w, h)
                    dgv.Rows.Item(dgvIndex).Height = h
                    dgv.Rows.Item(dgvIndex).Cells(dgvColumn).Value = bmp.Clone
                End Using
            End Using
        End Sub
    End Class

    • Marked as answer by srajmuneer Saturday, May 27, 2017 7:16 PM
    Saturday, May 27, 2017 12:26 AM
  • The users holds ctrl key to multiselect from the listbox.

    Imports System.Drawing.Printing
    
    Public Class Form5
        Private WithEvents button1 As New Button With {.Parent = Me, .Text = "Print"}
        Private WithEvents list1 As New ListBox With {.Parent = Me, .Location = New Point(10, 30), .Height = 200}
        Private WithEvents PrintDocument1 As PrintDocument = New PrintDocument
        Private PrintPreviewDialog1 As New PrintPreviewDialog
        Private SoureFolder As String = "c:\bitmaps\"
        Private PageCount As Integer
    
        Private Sub PrintingPicture_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            list1.SelectionMode = SelectionMode.MultiSimple
    
            Dim di As New IO.DirectoryInfo(SoureFolder)
            Dim aryFi As IO.FileInfo() = di.GetFiles("*.jpg")
            Dim fi As IO.FileInfo
    
            For Each fi In aryFi
                list1.Items.Add(fi.Name)
            Next
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                'call the print dialog
                'click the print button on the dialog to print
                PageCount = 0
                PrintPreviewDialog1.Document = PrintDocument1
                PrintPreviewDialog1.ShowDialog()
    
            Catch ex As Exception
                MsgBox("Printing Problem" & Chr(13) & ex.Message, MsgBoxStyle.Exclamation)
            End Try
        End Sub
    
        Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
            'draws PictureBox1.Image on printer graphics maintains image ratio, 
            'fits pic to largest border size
            Dim img As Image = Image.FromFile(SoureFolder & list1.SelectedItems(PageCount).ToString)
    
            Dim l, t, w, h As Integer
            Dim ratio As Single = CSng(img.Width / img.Height)
    
            If ratio > e.MarginBounds.Width / e.MarginBounds.Height Then
                    w = e.MarginBounds.Width
                    h = CInt(w / ratio)
                    t = CInt(e.MarginBounds.Top + (e.MarginBounds.Height / 2) - (h / 2))
                    l = e.MarginBounds.Left
                Else
                    h = e.MarginBounds.Height
                    w = CInt(h * ratio)
                    l = CInt(e.MarginBounds.Left + (e.MarginBounds.Width / 2) - (w / 2))
                    t = e.MarginBounds.Top
                End If
    
            'draw the image on the printer graphics
            e.Graphics.DrawImage(img, l, t, w, h)
            img.Dispose()
    
            PageCount += 1
    
            If PageCount >= list1.SelectedItems.Count Then
                e.HasMorePages = False
            Else
                e.HasMorePages = True
            End If
    
        End Sub
    End Class

    • Marked as answer by srajmuneer Tuesday, May 30, 2017 1:08 AM
    Monday, May 29, 2017 10:47 AM
  •  This is because the PrintPage event is called once for each selected image when the PrintPreviewDialog is opened which runs PageCount up to the number of selected images,  then when you press Print on the PrintPreviewDialog,  it calls the PrintPage event again,  once for each image.  However,  PageCount did not get reset back to 0 yet.

     So,  to fix that,  you can place one line in the PrintPage event as shown below to set PageCount back to 0 if there is no more pages.

            If PageCount >= ListBox1.SelectedItems.Count Then
                e.HasMorePages = False
                PageCount = 0 'add this line to set PageCount back to 0
            Else
                e.HasMorePages = True
            End If
    


    If you say it can`t be done then i`ll try it

    • Marked as answer by srajmuneer Saturday, June 3, 2017 10:08 AM
    Saturday, June 3, 2017 10:03 AM
  • I want :

    1. display names pictures from folder into Listbox .
    2. when click on item name Picture in Listbox to display Picture in PictureBox
    3. I want use all format image

    Hi

    Give this a try

    ' Form1 with ListBox1, PictureBox1
    ' and FolderBrowserDialog1
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim d As New Dictionary(Of String, String)
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' this would be better off in a
            ' Button Click event
            FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            Dim response As DialogResult = FolderBrowserDialog1.ShowDialog
            If response = DialogResult.OK Then
                If FolderBrowserDialog1.SelectedPath.Length > 0 Then
                    Dim pictFolder As String = FolderBrowserDialog1.SelectedPath
                    For Each f As String In My.Computer.FileSystem.GetFiles(pictFolder)
                        d.Add(f, IO.Path.GetFileNameWithoutExtension(f))
                    Next
                End If
            End If
            ListBox1.DisplayMember = "value"
            ListBox1.ValueMember = "key"
            ListBox1.DataSource = New BindingSource(d, Nothing)
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
            PictureBox1.Image = Image.FromFile(ListBox1.SelectedValue.ToString)
        End Sub
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by srajmuneer Thursday, May 25, 2017 5:18 PM
    Thursday, May 25, 2017 4:04 PM
  • thanks , when click button print and preview image into PrintPreviewDialog don't Scaling image :

    I want Scaling image for printing to Fit image in Page Print Preview





    You need to learn how it works then you can modify it many ways to do exactly what you want.

    The previous routine fits the image to the widest dimension and maintains the aspect ratio of the original image. This stretches the image to fit the margins in all directions.

    If you have additional questions you should start a new post and try to describe exactly what you want to do.

       Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
            'draws Image on printer graphics stretch fit to margins
            Dim img As Image = Image.FromFile(SoureFolder & list1.SelectedItems(PageCount).ToString)
    
            'draw the image on the printer graphics
            e.Graphics.DrawImage(img, e.MarginBounds)
            img.Dispose()
    
            PageCount += 1
    
            If PageCount >= list1.SelectedItems.Count Then
                e.HasMorePages = False
            Else
                e.HasMorePages = True
            End If
    
        End Sub


    • Marked as answer by srajmuneer Wednesday, May 31, 2017 3:23 PM
    Wednesday, May 31, 2017 1:29 PM
  • thanks all for help ,hi tommytwotrain Your code is correct and there is no problem with it, but sometimes I need to go back re-selected the images for the second time after the display (PrintDocument) , I understand code when copy from the forum and I know the problem is to put (PageCount) in the right place and Reset value PageCount but I tried to put the (PageCount) in several places but did not work with me It was the final and Experienced code is running :

     Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
            Try
                'draws Image on printer graphics stretch fit to margins
                Dim img As Image = Image.FromFile(SoureFolder & listbox1.SelectedItems(PageCount).ToString)
    
                'draw the image on the printer graphics
                e.Graphics.DrawImage(img, e.MarginBounds)
                img.Dispose()
                PageCount += 1
                If PageCount >= listbox1.SelectedItems.Count Then
                    e.HasMorePages = False
                    PageCount = 0 'add this line to set PageCount back to 0
                Else
                    e.HasMorePages = True
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
          
        End Sub
    This is thanks to Mr. tommytwotrain and Mr. IronRazerz for Help me and My thanks and gratitude to you


    Yes well you have a simple print routine so you dont get errors in it but in a more complex situation you can get unexpected errors in the print routine and the execution will jump out of the print routine without resetting the counter.

    So if you have a multipage doc and only set the counter in the print routine you will not be able to print again after an error. Edit: in some cases.

    That is all I am saying.



    • Edited by tommytwotrain Saturday, June 3, 2017 3:54 PM
    • Marked as answer by srajmuneer Saturday, June 3, 2017 6:16 PM
    Saturday, June 3, 2017 3:51 PM
  • can clear ListBox1.DataSource I try clear but show error :


    Hi

    That fails because the ListBox has the data bound to it.

    Here is an amended version using a Button1 to Clear both th ListBox and the PictureBox

    ' Form1 with ListBox1, PictureBox1
    ' and FolderBrowserDialog1
    ' and Button1 (for Clear)
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim d As New Dictionary(Of String, String)
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' this would be better off in a
            ' Button Click event
            FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            Dim response As DialogResult = FolderBrowserDialog1.ShowDialog
            If response = DialogResult.OK Then
                If FolderBrowserDialog1.SelectedPath.Length > 0 Then
                    Dim pictFolder As String = FolderBrowserDialog1.SelectedPath
                    For Each f As String In My.Computer.FileSystem.GetFiles(pictFolder)
                        d.Add(f, IO.Path.GetFileNameWithoutExtension(f))
                    Next
                End If
            End If
            ListBox1.DisplayMember = "value"
            ListBox1.ValueMember = "key"
            ListBox1.DataSource = New BindingSource(d, Nothing)
    
    
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
            If ListBox1.SelectedValue Is Nothing Then Exit Sub
            PictureBox1.Image = Image.FromFile(ListBox1.SelectedValue.ToString)
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            ' sets datasource to nothing
            ' and clears PictureBox
            ListBox1.DataSource = Nothing
            PictureBox1.Image = Nothing
        End Sub
    End Class
    


    Regards Les, Livingston, Scotland

    • Marked as answer by srajmuneer Friday, May 26, 2017 6:43 AM
    Thursday, May 25, 2017 7:17 PM

All replies

  • I want :

    1. display names pictures from folder into Listbox .
    2. when click on item name Picture in Listbox to display Picture in PictureBox
    3. I want use all format image

    Hi

    Give this a try

    ' Form1 with ListBox1, PictureBox1
    ' and FolderBrowserDialog1
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim d As New Dictionary(Of String, String)
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' this would be better off in a
            ' Button Click event
            FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            Dim response As DialogResult = FolderBrowserDialog1.ShowDialog
            If response = DialogResult.OK Then
                If FolderBrowserDialog1.SelectedPath.Length > 0 Then
                    Dim pictFolder As String = FolderBrowserDialog1.SelectedPath
                    For Each f As String In My.Computer.FileSystem.GetFiles(pictFolder)
                        d.Add(f, IO.Path.GetFileNameWithoutExtension(f))
                    Next
                End If
            End If
            ListBox1.DisplayMember = "value"
            ListBox1.ValueMember = "key"
            ListBox1.DataSource = New BindingSource(d, Nothing)
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
            PictureBox1.Image = Image.FromFile(ListBox1.SelectedValue.ToString)
        End Sub
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by srajmuneer Thursday, May 25, 2017 5:18 PM
    Thursday, May 25, 2017 4:04 PM
  • thanks leshay for help 
    Thursday, May 25, 2017 5:18 PM
  • can clear ListBox1.DataSource I try clear but show error :


    • Edited by srajmuneer Thursday, May 25, 2017 6:59 PM
    Thursday, May 25, 2017 6:59 PM
  • can clear ListBox1.DataSource I try clear but show error :


    Hi

    That fails because the ListBox has the data bound to it.

    Here is an amended version using a Button1 to Clear both th ListBox and the PictureBox

    ' Form1 with ListBox1, PictureBox1
    ' and FolderBrowserDialog1
    ' and Button1 (for Clear)
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim d As New Dictionary(Of String, String)
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' this would be better off in a
            ' Button Click event
            FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            Dim response As DialogResult = FolderBrowserDialog1.ShowDialog
            If response = DialogResult.OK Then
                If FolderBrowserDialog1.SelectedPath.Length > 0 Then
                    Dim pictFolder As String = FolderBrowserDialog1.SelectedPath
                    For Each f As String In My.Computer.FileSystem.GetFiles(pictFolder)
                        d.Add(f, IO.Path.GetFileNameWithoutExtension(f))
                    Next
                End If
            End If
            ListBox1.DisplayMember = "value"
            ListBox1.ValueMember = "key"
            ListBox1.DataSource = New BindingSource(d, Nothing)
    
    
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
            If ListBox1.SelectedValue Is Nothing Then Exit Sub
            PictureBox1.Image = Image.FromFile(ListBox1.SelectedValue.ToString)
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            ' sets datasource to nothing
            ' and clears PictureBox
            ListBox1.DataSource = Nothing
            PictureBox1.Image = Nothing
        End Sub
    End Class
    


    Regards Les, Livingston, Scotland

    • Marked as answer by srajmuneer Friday, May 26, 2017 6:43 AM
    Thursday, May 25, 2017 7:17 PM
  • Hi

    Slow day here today. Decided to revisit this code.

    Here is a more considered version. Uses an empty Form1 and creates controls at run time. Adds size mode buttons.

    ' blank Form1
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim d As New Dictionary(Of String, String)
        Dim PicTypes As New List(Of String)
        Dim lb As New ListBox
        Dim pb As New PictureBox
        Dim b1, b2, b3, b4, b5 As New Button
        Dim lab As New Label
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

            ' set up allows image types
            ' lower case only
            PicTypes.AddRange({".jpg", ".jpeg", "bmp", ".png"})

            ' set up initial folder path
            FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments


            Size = New Size(600, 500)

            ' set up controls
            With lb
                .Location = New Point(10, 8)
                .Size = New Size(110, 334)
                .Font = New Font(lb.Font.FontFamily, 10)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom
            End With
            With pb
                .Location = New Point(128, 8)
                .Size = New Size(450, 416)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom Or AnchorStyles.Right
                ' set initial PB image size mode
                .SizeMode = PictureBoxSizeMode.Zoom
                SetBC("b3")
            End With
            With lab
                .AutoSize = False
                .TextAlign = ContentAlignment.MiddleLeft
                .Location = New Point(10, 430)
                .Size = New Size(568, 24)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom Or AnchorStyles.Right
            End With
            With b1
                .Text = "Choose Folder"
                .Size = New Size(lb.Width, 26)
                .Location = New Point(10, 334)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b2
                .Text = "Normal"
                .Size = New Size(54, 26)
                .Location = New Point(10, 370)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b3
                .Text = "Zoom"
                .Size = New Size(54, 26)
                .Location = New Point(66, 370)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b4
                .Text = "Stretch"
                .Size = New Size(54, 26)
                .Location = New Point(10, 398)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
            With b5
                .Text = "Center"
                .Size = New Size(54, 26)
                .Location = New Point(66, 398)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With

            ' add controls to Form1
            Controls.AddRange({lb, pb, lab, b1, b2, b3, b4, b5})

            ' create control handlers
            AddHandler lb.SelectedIndexChanged, AddressOf LB_SIC
            AddHandler b1.Click, AddressOf B1_Click
            AddHandler b2.Click, AddressOf B2_Click
            AddHandler b3.Click, AddressOf B3_Click
            AddHandler b4.Click, AddressOf B4_Click
            AddHandler b5.Click, AddressOf B5_Click

        End Sub
        Private Sub LB_SIC(sender As Object, e As EventArgs)
            Dim lb As ListBox = DirectCast(sender, ListBox)
            If lb.SelectedIndex < 0 Then Exit Sub
            Try
                pb.Image = Image.FromFile(lb.SelectedValue.ToString)
                lab.Text = lb.SelectedValue.ToString
            Catch ex As Exception
                MessageBox.Show("ERROR: can't load " & vbCrLf & lb.SelectedValue.ToString)
            End Try
        End Sub
        Private Sub B1_Click(sender As Object, e As EventArgs)
            Dim response As DialogResult = FolderBrowserDialog1.ShowDialog
            If response = DialogResult.OK Then
                lb.DataSource = Nothing
                d.Clear()
                pb.Image = Nothing
                If FolderBrowserDialog1.SelectedPath.Length > 0 Then
                    Dim pictFolder As String = FolderBrowserDialog1.SelectedPath
                    For Each f As String In My.Computer.FileSystem.GetFiles(pictFolder)
                        If PicTypes.Contains(IO.Path.GetExtension(f.ToLower)) Then
                            d.Add(f, IO.Path.GetFileNameWithoutExtension(f))
                        End If
                    Next
                End If
                If d.Count > 0 Then
                    lb.DisplayMember = "value"
                    lb.ValueMember = "key"
                    lb.DataSource = New BindingSource(d, Nothing)
                Else
                    lab.Text = Nothing
                End If
            End If
        End Sub
        Private Sub SetBC(s As String)
            Dim c1 As Color = Color.LightBlue
            Dim c2 As Color = Color.FromKnownColor(KnownColor.Control)

            b2.BackColor = c2
            b3.BackColor = c2
            b4.BackColor = c2
            b5.BackColor = c2

            Select Case s
                Case "b2"
                    b2.BackColor = c1
                Case "b3"
                    b3.BackColor = c1
                Case "b4"
                    b4.BackColor = c1
                Case "b5"
                    b5.BackColor = c1
            End Select
        End Sub
        Private Sub B2_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.Normal
            SetBC("b2")
        End Sub
        Private Sub B3_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.Zoom
            SetBC("b3")
        End Sub
        Private Sub B4_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.StretchImage
            SetBC("b4")
        End Sub
        Private Sub B5_Click(sender As Object, e As EventArgs)
            pb.SizeMode = PictureBoxSizeMode.CenterImage
            SetBC("b5")
        End Sub
    End Class



    Regards Les, Livingston, Scotland



    • Edited by leshay Friday, May 26, 2017 9:22 PM IronRazerz suggestion
    • Marked as answer by srajmuneer Saturday, May 27, 2017 7:39 PM
    Friday, May 26, 2017 6:27 PM
  •  leshay, you might want to use the String.ToLower method in this line just in case the file extensions have capital letters like ".BMP" or ".Jpg".   8)

    If PicTypes.Contains(IO.Path.GetExtension(f).ToLower) Then


    If you say it can`t be done then i`ll try it

    Friday, May 26, 2017 8:40 PM
  •  leshay, you might want to use the String.ToLower method in this line just in case the file extensions have capital letters like ".BMP" or ".Jpg".   8)

    If PicTypes.Contains(IO.Path.GetExtension(f).ToLower) Then


    If you say it can`t be done then i`ll try it

    Hi IronRazerz

    Good thinking batman .................

    Thanks


    Regards Les, Livingston, Scotland


    • Edited by leshay Friday, May 26, 2017 9:25 PM
    Friday, May 26, 2017 9:19 PM
  •  Here is another quick example.  It requires 1 PictureBox,  1 Button,  and  1 ListBox added to the form.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using fb As New FolderBrowserDialog
                fb.Description = "Select A Folder With Images"
                If fb.ShowDialog = DialogResult.OK Then
                    ListBox1.DataSource = Nothing
                    ListBox1.DataSource = New IO.DirectoryInfo(fb.SelectedPath).GetFiles("*.*").Where(Function(x) ".jpg.jpeg.bmp.gif.png".Contains(IO.Path.GetExtension(x.FullName).ToLower)).ToList
                    ListBox1.DisplayMember = "Name"
                    ListBox1.ValueMember = "FullName"
                End If
            End Using
        End Sub
    
        Private Sub ListBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedValueChanged
            If ListBox1.SelectedValue IsNot Nothing Then PictureBox1.ImageLocation = ListBox1.SelectedValue.ToString
        End Sub
    End Class
    


    If you say it can`t be done then i`ll try it

    • Marked as answer by srajmuneer Saturday, May 27, 2017 7:19 PM
    Friday, May 26, 2017 10:44 PM
  • This one uses a DataGridView.  :)

    Public Class Form6
        Private WithEvents dgv As New DataGridView With {.Parent = Me, .Dock = DockStyle.Right,
            .Width = 300, .RowHeadersVisible = False}
        Private WithEvents OpenButton As New Button With {.Parent = Me,
            .Location = New Point(50, 10), .Text = "Open..."}
        Private Picture1 As New Button With {.Parent = Me}
        Private CurrentFolder As String = "c:\bitmaps\"
    
        Private Sub Form6_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ClientSize = New Size(600, 500)
            Picture1.BackgroundImageLayout = ImageLayout.Zoom
            Form6_Resize(0, Nothing)
            FillDgv(dgv, CurrentFolder)
        End Sub
    
        Private Sub Form6_Resize(sender As Object, e As EventArgs) Handles Me.Resize
            Picture1.Location = New Point(0, OpenButton.Bottom + 10)
            Picture1.Size = New Size(ClientSize.Width - dgv.Width, ClientSize.Height - Picture1.Top)
        End Sub
    
        Private Sub OpenButton_Click(sender As Object, e As EventArgs) Handles OpenButton.Click
            Using dialog As New FolderBrowserDialog()
                dialog.RootFolder = Environment.SpecialFolder.Desktop
                dialog.SelectedPath = CurrentFolder
                dialog.Description = "Select a Folder"
                If dialog.ShowDialog() = DialogResult.OK Then
                    CurrentFolder = dialog.SelectedPath
                    FillDgv(dgv, CurrentFolder)
                End If
            End Using
        End Sub
    
        Private Sub dgv_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellClick
            If e.RowIndex > -1 Then
                'dispose old image
                Dim img As Image = Nothing
                If Picture1.BackgroundImage IsNot Nothing Then img = Picture1.BackgroundImage
    
                Picture1.BackgroundImage = Image.FromFile(dgv.Rows.Item(e.RowIndex).Cells(0).Tag)
                Picture1.Refresh()
    
                If img IsNot Nothing Then img.Dispose()
            End If
        End Sub
    
        Private Sub FillDgv(thisDgv As DataGridView, thisFilePath As String)
            With thisDgv
                .Rows.Clear()
                .Columns.Clear()
                .Columns.Add("FileName", "File Name: ")
    
                Dim img As New DataGridViewImageColumn()
                img.Name = "Image"
                img.Width = 160
                dgv.Columns.Add(img)
    
                'fill the dgv with the files in this folder
                Dim di As New IO.DirectoryInfo(thisFilePath)
                Dim aryFi As IO.FileInfo() = di.GetFiles("*.png")
                Dim fi As IO.FileInfo
    
                For Each fi In aryFi
                    Dim n As Integer = dgv.Rows.Add()
                    .Rows.Item(n).Cells(0).Value = fi.Name
                    .Rows.Item(n).Cells(0).Tag = fi.FullName
                    MakeDGVThumbnail(fi.FullName, dgv, n, 1)
                Next
            End With
        End Sub
    
        Private Sub MakeDGVThumbnail(theFilenamePath As String, dgv As DataGridView, dgvIndex As Integer, dgvColumn As Integer)
            Dim thisBmp As Bitmap = New Bitmap(theFilenamePath)
            Dim w As Integer = thisBmp.Width
            Dim h As Integer = thisBmp.Height
            Dim ratio As Single = CSng(h / w)
    
            w = dgv.Columns(dgvColumn).Width
    
            If ratio > 1 Then
                h = 100
                w = CInt(h / ratio)
            Else
                h = CInt(w * ratio)
            End If
    
            Using bmp As New Bitmap(w, h)
                Using g As Graphics = Graphics.FromImage(bmp)
                    g.DrawImage(thisBmp, 0, 0, w, h)
                    dgv.Rows.Item(dgvIndex).Height = h
                    dgv.Rows.Item(dgvIndex).Cells(dgvColumn).Value = bmp.Clone
                End Using
            End Using
        End Sub
    End Class

    • Marked as answer by srajmuneer Saturday, May 27, 2017 7:16 PM
    Saturday, May 27, 2017 12:26 AM
  • thanks IronRazerz your code is very easy again thank you very very much for help  
    Saturday, May 27, 2017 7:21 PM
  • Hi

    Yet another version.

    This time I tried to implement a simple click to drag/move and wheel to zoom instead of buttons for PictureBox size mode. A very basic example. Seems to work OK as far as I can see.

    ' blank Form1
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim d As New Dictionary(Of String, String)
        Dim PicTypes As New List(Of String)
        Dim lb As New ListBox
        Dim WithEvents pb As New PictureBox
        Dim b1 As New Button
        Dim lab As New Label
        Dim im As Image
        Dim sc As Single = 0.5
        Dim mx As Integer = 0
        Dim my As Integer = 0
        Dim x, y As Integer
        Dim Drag As Boolean = False
        Dim whStep As Single = 0.1
        Dim maxZoom As Integer = 5
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            ' set up allows image types
            ' lower case only
            PicTypes.AddRange({".jpg", ".jpeg", "bmp", ".png", ".tif"})
    
            ' set up initial folder path
            FolderBrowserDialog1.SelectedPath = WindowsApp1.My.Computer.FileSystem.SpecialDirectories.MyDocuments
    
            Size = New Size(600, 500)
    
            ' set up controls
            With lb
                .Location = New Point(10, 8)
                .Size = New Size(110, 392)
                .Font = New Font(lb.Font.FontFamily, 10)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom
            End With
            With pb
                .Location = New Point(128, 8)
                .Size = New Size(450, 416)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom Or AnchorStyles.Right
            End With
            With lab
                .AutoSize = False
                .TextAlign = ContentAlignment.MiddleLeft
                .Location = New Point(10, 430)
                .Size = New Size(568, 24)
                .BorderStyle = BorderStyle.FixedSingle
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom Or AnchorStyles.Right
            End With
            With b1
                .Text = "Choose Folder"
                .Size = New Size(lb.Width, 26)
                .Location = New Point(10, 396)
                .Anchor = AnchorStyles.Left Or AnchorStyles.Bottom
            End With
    
            ' add controls to Form1
            Controls.AddRange({lb, pb, lab, b1})
    
            ' create control handlers
            AddHandler lb.SelectedIndexChanged, AddressOf LB_SIC
            AddHandler b1.Click, AddressOf B1_Click
        End Sub
        Private Sub LB_SIC(sender As Object, e As EventArgs)
            Dim lb As ListBox = DirectCast(sender, ListBox)
            If lb.SelectedIndex < 0 Then Exit Sub
            sc = 1
            mx = 0
            my = 0
            Try
                im = Image.FromFile(lb.SelectedValue.ToString)
                pb.Invalidate()
                lab.Text = lb.SelectedValue.ToString
            Catch ex As Exception
                MessageBox.Show("ERROR: can't load " & vbCrLf & lb.SelectedValue.ToString & vbCrLf & ex.Message)
            End Try
        End Sub
        Private Sub pb_Paint(sender As Object, e As PaintEventArgs) Handles pb.Paint
            If im Is Nothing Then Exit Sub
            e.Graphics.ScaleTransform(sc, sc)
            e.Graphics.DrawImage(im, New Point(mx, my))
        End Sub
        Private Sub pb_MouseMove(sender As Object, e As MouseEventArgs) Handles pb.MouseMove
            If Drag Then
                mx = (e.X - x)
                my = (e.Y - y)
                pb.Invalidate()
            End If
        End Sub
        Private Sub pb_MouseDown(sender As Object, e As MouseEventArgs) Handles pb.MouseDown
            Drag = True
            x = e.X - mx
            y = e.Y - my
        End Sub
        Private Sub pb_MouseUp(sender As Object, e As MouseEventArgs) Handles pb.MouseUp
            Drag = False
        End Sub
        Private Sub pb_MouseWheel(sender As Object, e As MouseEventArgs) Handles pb.MouseWheel
            Dim myDelta As Double = (e.Delta * whStep) / 120
            If myDelta <> 0 Then
                sc += CSng(myDelta)
                If sc < 0.1 Then sc = 0.1
                If sc > maxZoom Then sc = maxZoom
            End If
            pb.Invalidate()
        End Sub
        Private Sub B1_Click(sender As Object, e As EventArgs)
            Dim response As DialogResult = FolderBrowserDialog1.ShowDialog
            If response = DialogResult.OK Then
                lb.DataSource = Nothing
                d.Clear()
                pb.Image = Nothing
                If FolderBrowserDialog1.SelectedPath.Length > 0 Then
                    Dim pictFolder As String = FolderBrowserDialog1.SelectedPath
                    For Each f As String In WindowsApp1.My.Computer.FileSystem.GetFiles(pictFolder)
                        If PicTypes.Contains(IO.Path.GetExtension(f).ToLower) Then
                            d.Add(f, IO.Path.GetFileNameWithoutExtension(f))
                        End If
                    Next
                End If
                If d.Count > 0 Then
                    lb.DisplayMember = "value"
                    lb.ValueMember = "key"
                    lb.DataSource = New BindingSource(d, Nothing)
                Else
                    lab.Text = Nothing
                End If
            End If
        End Sub
    End Class


    Regards Les, Livingston, Scotland

    Sunday, May 28, 2017 6:54 PM
  • thank you very much for help leshay , Last question The possibility to print a picture or a collection of images from the listbox I mean custom choose images to Print can this ? 

    • Edited by srajmuneer Monday, May 29, 2017 7:10 AM
    Monday, May 29, 2017 12:39 AM
  • The users holds ctrl key to multiselect from the listbox.

    Imports System.Drawing.Printing
    
    Public Class Form5
        Private WithEvents button1 As New Button With {.Parent = Me, .Text = "Print"}
        Private WithEvents list1 As New ListBox With {.Parent = Me, .Location = New Point(10, 30), .Height = 200}
        Private WithEvents PrintDocument1 As PrintDocument = New PrintDocument
        Private PrintPreviewDialog1 As New PrintPreviewDialog
        Private SoureFolder As String = "c:\bitmaps\"
        Private PageCount As Integer
    
        Private Sub PrintingPicture_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            list1.SelectionMode = SelectionMode.MultiSimple
    
            Dim di As New IO.DirectoryInfo(SoureFolder)
            Dim aryFi As IO.FileInfo() = di.GetFiles("*.jpg")
            Dim fi As IO.FileInfo
    
            For Each fi In aryFi
                list1.Items.Add(fi.Name)
            Next
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Try
                'call the print dialog
                'click the print button on the dialog to print
                PageCount = 0
                PrintPreviewDialog1.Document = PrintDocument1
                PrintPreviewDialog1.ShowDialog()
    
            Catch ex As Exception
                MsgBox("Printing Problem" & Chr(13) & ex.Message, MsgBoxStyle.Exclamation)
            End Try
        End Sub
    
        Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
            'draws PictureBox1.Image on printer graphics maintains image ratio, 
            'fits pic to largest border size
            Dim img As Image = Image.FromFile(SoureFolder & list1.SelectedItems(PageCount).ToString)
    
            Dim l, t, w, h As Integer
            Dim ratio As Single = CSng(img.Width / img.Height)
    
            If ratio > e.MarginBounds.Width / e.MarginBounds.Height Then
                    w = e.MarginBounds.Width
                    h = CInt(w / ratio)
                    t = CInt(e.MarginBounds.Top + (e.MarginBounds.Height / 2) - (h / 2))
                    l = e.MarginBounds.Left
                Else
                    h = e.MarginBounds.Height
                    w = CInt(h * ratio)
                    l = CInt(e.MarginBounds.Left + (e.MarginBounds.Width / 2) - (w / 2))
                    t = e.MarginBounds.Top
                End If
    
            'draw the image on the printer graphics
            e.Graphics.DrawImage(img, l, t, w, h)
            img.Dispose()
    
            PageCount += 1
    
            If PageCount >= list1.SelectedItems.Count Then
                e.HasMorePages = False
            Else
                e.HasMorePages = True
            End If
    
        End Sub
    End Class

    • Marked as answer by srajmuneer Tuesday, May 30, 2017 1:08 AM
    Monday, May 29, 2017 10:47 AM
  • thanks tommytwotrain for help
    Tuesday, May 30, 2017 1:08 AM
  • hi tommytwotrain , can print images to full size in PrintDocument for your code :

     If ratio > e.MarginBounds.Width / e.MarginBounds.Height Then
                    w = e.MarginBounds.Width
                    h = CInt(w / ratio)
                    t = CInt(e.MarginBounds.Top + (e.MarginBounds.Height / 2) - (h / 2))
                    l = e.MarginBounds.Left
                Else
                    h = e.MarginBounds.Height
                    w = CInt(h * ratio)
                    l = CInt(e.MarginBounds.Left + (e.MarginBounds.Width / 2) - (w / 2))
                    t = e.MarginBounds.Top
                End If
    
    

     
    Wednesday, May 31, 2017 9:49 AM
  • hi tommytwotrain , can print images to full size in PrintDocument for your code :

     If ratio > e.MarginBounds.Width / e.MarginBounds.Height Then
                    w = e.MarginBounds.Width
                    h = CInt(w / ratio)
                    t = CInt(e.MarginBounds.Top + (e.MarginBounds.Height / 2) - (h / 2))
                    l = e.MarginBounds.Left
                Else
                    h = e.MarginBounds.Height
                    w = CInt(h * ratio)
                    l = CInt(e.MarginBounds.Left + (e.MarginBounds.Width / 2) - (w / 2))
                    t = e.MarginBounds.Top
                End If
    

     

    I don't understand the question.

    The code fits the image to the size of the print page margins. Do you want to do something else? What exactly? Maybe show a picture of the result you want.

    Wednesday, May 31, 2017 11:55 AM
  • thanks , when click button print and preview image into PrintPreviewDialog don't Scaling image :

    I want Scaling image for printing to Fit image in Page Print Preview






    • Edited by srajmuneer Wednesday, May 31, 2017 1:20 PM
    Wednesday, May 31, 2017 1:13 PM
  • thanks , when click button print and preview image into PrintPreviewDialog don't Scaling image :

    I want Scaling image for printing to Fit image in Page Print Preview





    You need to learn how it works then you can modify it many ways to do exactly what you want.

    The previous routine fits the image to the widest dimension and maintains the aspect ratio of the original image. This stretches the image to fit the margins in all directions.

    If you have additional questions you should start a new post and try to describe exactly what you want to do.

       Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
            'draws Image on printer graphics stretch fit to margins
            Dim img As Image = Image.FromFile(SoureFolder & list1.SelectedItems(PageCount).ToString)
    
            'draw the image on the printer graphics
            e.Graphics.DrawImage(img, e.MarginBounds)
            img.Dispose()
    
            PageCount += 1
    
            If PageCount >= list1.SelectedItems.Count Then
                e.HasMorePages = False
            Else
                e.HasMorePages = True
            End If
    
        End Sub


    • Marked as answer by srajmuneer Wednesday, May 31, 2017 3:23 PM
    Wednesday, May 31, 2017 1:29 PM
  • thank you very much for help , I've been wonderful in answers
    • Edited by srajmuneer Wednesday, May 31, 2017 3:27 PM
    Wednesday, May 31, 2017 3:23 PM
  • hi tommytwotrain , I had a problem when I re-selected the images for the second time after the display (PrintDocument) This problem appears:

    Saturday, June 3, 2017 8:25 AM
  •  This is because the PrintPage event is called once for each selected image when the PrintPreviewDialog is opened which runs PageCount up to the number of selected images,  then when you press Print on the PrintPreviewDialog,  it calls the PrintPage event again,  once for each image.  However,  PageCount did not get reset back to 0 yet.

     So,  to fix that,  you can place one line in the PrintPage event as shown below to set PageCount back to 0 if there is no more pages.

            If PageCount >= ListBox1.SelectedItems.Count Then
                e.HasMorePages = False
                PageCount = 0 'add this line to set PageCount back to 0
            Else
                e.HasMorePages = True
            End If
    


    If you say it can`t be done then i`ll try it

    • Marked as answer by srajmuneer Saturday, June 3, 2017 10:08 AM
    Saturday, June 3, 2017 10:03 AM
  • thanks IronRazerz for help
    Saturday, June 3, 2017 10:08 AM
  • hi tommytwotrain , I had a problem when I re-selected the images for the second time after the display (PrintDocument) This problem appears:

    When you copy code from the forum you need to learn how it works or you will not be able to use the code in your project in the future because you don't understand it.

    You get that error because PageCount is larger than the number of selected items.

    Do you understand what PageCount does?

    What is PageCount when you get the error? What is ListBox1.SelectedItems.count? Why would they be those values? What value should pagecount be? What value is PageCount the first time you call the routine? And what is PageCount the second time you call the routine?

    Where else in my first print example does PageCount get set to a value?

    Also notice how my example has a try catch in the button click. You should use an error handler like this for cases where the printer is not ready so your program wont crash if the printer is off line or something. And that means you should set the pagecount where I do in my example. I dont think your app will recover properly from a printer error if you set it as in Razerz example which is not using the error handler.

    When you post a question you should show all the code related to your question. If your example code is incomplete then you get incomplete answers.

    :)

    Saturday, June 3, 2017 10:24 AM
  •  I dont think your app will recover properly from a printer error if you set it as in Razerz example which is not using the error handler.

     What?  My example only showed to reset PageCount back to 0 when there is no more pages,  nothing else.  You need to do that or it throws the Index out of range exception when you press the Print button on the PrintPreviewDialog.  That is because the PrintPage event has already ran PageCount up to the number of selected images when the PrintPreviewDialog is opened.

     However,  yes i would still keep setting PageCount back to 0 in the Button Click event that opens the PrintPreviewDialog just in case.   8)

    EDIT:  Oh,  maybe you mean in the other question i helped with yesterday.  That was just a quick example and it probably would be better to use a Try/Catch.


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Saturday, June 3, 2017 10:43 AM
    Saturday, June 3, 2017 10:38 AM
  •  I dont think your app will recover properly from a printer error if you set it as in Razerz example which is not using the error handler.

     What?  My example only showed to reset PageCount back to 0 when there is no more pages,  nothing else.  You need to do that or it throws the Index out of range exception when you press the Print button on the PrintPreviewDialog.  That is because the PrintPage event has already ran PageCount up to the number of selected images when the PrintPreviewDialog is opened.

     However,  yes i would still keep setting PageCount back to 0 in the Button Click event that opens the PrintPreviewDialog just in case.   8)

    EDIT:  Oh,  maybe you mean in the other question i helped with yesterday.  That was just a quick example and it probably would be better to use a Try/Catch.


    If you say it can`t be done then i`ll try it


    Well I have not tested it lately but I think if say the printer runs out of paper on page 2 of a four page printout print page routine will throw an error and exit the sub without resetting pagecount = 0.

    Assuming you use an error handler as I show my first print example in this thread, if you try to print again with say 1 item selected you will get a another error on the pagecount larger than selected.count.

    Its early I could be wrong.

    PS I guess maybe running out of paper wont do it but I know there are cases where it will jump out of the print routine and then the pagecounter never gets reset. Just cant think of a good one now.

    I guess if my print code tried to divide by zero for some reason unknown then it will happen.



    Saturday, June 3, 2017 10:49 AM
  • Well I have not tested it lately but I think if say the printer runs out of paper on page 2 of a four page printout print page routine will throw an error and exit the sub without resetting pagecount = 0.

     Yeah,  that is why i said that i would still keep setting PageCount back to 0 in the Button Click event too.  However,  it still has to be done when there is no more pages because of the reasons i explained in last post.   8)

     Not sure about errors,  i have not experienced any in the few printing examples i have done.  Still good to expect some sometimes though.  8)


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Saturday, June 3, 2017 11:14 AM
    Saturday, June 3, 2017 11:11 AM
  • Well I have not tested it lately but I think if say the printer runs out of paper on page 2 of a four page printout print page routine will throw an error and exit the sub without resetting pagecount = 0.

     Yeah,  that is why i said that i would still keep setting PageCount back to 0 in the Button Click event too.  However,  it still has to be done when there is no more pages because of the reasons i explained in last post.   8)

     Not sure about errors,  i have not experienced any in the few printing examples i have done.  Still good to expect some sometimes though.  8)


    If you say it can`t be done then i`ll try it

    Yes well I have experienced plenty. And if you only reset the count at the end of the print routine then you will have the problem. Thats why I brought it up for you.

    Just my additional advice always wrap any printing functions with error handler and reset all counters before starting not when ending.


    :)
    Saturday, June 3, 2017 11:30 AM
  • Well I have not tested it lately but I think if say the printer runs out of paper on page 2 of a four page printout print page routine will throw an error and exit the sub without resetting pagecount = 0.

     Yeah,  that is why i said that i would still keep setting PageCount back to 0 in the Button Click event too.  However,  it still has to be done when there is no more pages because of the reasons i explained in last post.   8)

     Not sure about errors,  i have not experienced any in the few printing examples i have done.  Still good to expect some sometimes though.  8)


    If you say it can`t be done then i`ll try it

    Yes well I have experienced plenty. And if you only reset the count at the end of the print routine then you will have the problem. Thats why I brought it up for you.

    Just my additional advice always wrap any printing functions with error handler and reset all counters before starting not when ending.


    :)

    PS I guess you are right you have to do it in the print routine as well when calling print preview since that calls print routine twice, once for preview once for printing.

    Saturday, June 3, 2017 11:36 AM
  • PS I guess you are right you have to do it in the print routine as well when calling print preview since that calls print routine twice, once for preview once for printing.

     That's what i was getting at.  I was not saying to remove the reset from the button click event,  just to add the reset to the part that i showed.  You could probably do it in the PrintEnd event instead of in the PrintPage event.  It might call the PrintEnd event if it exits the PrintPage event for some unknown reason.  Not sure though,  i have not tried that yet.  8)

    If you say it can`t be done then i`ll try it

    Saturday, June 3, 2017 12:17 PM
  • thanks all for help ,hi tommytwotrain Your code is correct and there is no problem with it, but sometimes I need to go back re-selected the images for the second time after the display (PrintDocument) , I understand code when copy from the forum and I know the problem is to put (PageCount) in the right place and Reset value PageCount but I tried to put the (PageCount) in several places but did not work with me It was the final and Experienced code is running :

     Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
            Try
                'draws Image on printer graphics stretch fit to margins
                Dim img As Image = Image.FromFile(SoureFolder & listbox1.SelectedItems(PageCount).ToString)
    
                'draw the image on the printer graphics
                e.Graphics.DrawImage(img, e.MarginBounds)
                img.Dispose()
                PageCount += 1
                If PageCount >= listbox1.SelectedItems.Count Then
                    e.HasMorePages = False
                    PageCount = 0 'add this line to set PageCount back to 0
                Else
                    e.HasMorePages = True
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
          
        End Sub
    This is thanks to Mr. tommytwotrain and Mr. IronRazerz for Help me and My thanks and gratitude to you


    • Edited by srajmuneer Saturday, June 3, 2017 2:08 PM
    Saturday, June 3, 2017 2:06 PM
  •  You`re Welcome.  8)

    If you say it can`t be done then i`ll try it

    Saturday, June 3, 2017 2:14 PM
  • thanks all for help ,hi tommytwotrain Your code is correct and there is no problem with it, but sometimes I need to go back re-selected the images for the second time after the display (PrintDocument) , I understand code when copy from the forum and I know the problem is to put (PageCount) in the right place and Reset value PageCount but I tried to put the (PageCount) in several places but did not work with me It was the final and Experienced code is running :

     Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
            Try
                'draws Image on printer graphics stretch fit to margins
                Dim img As Image = Image.FromFile(SoureFolder & listbox1.SelectedItems(PageCount).ToString)
    
                'draw the image on the printer graphics
                e.Graphics.DrawImage(img, e.MarginBounds)
                img.Dispose()
                PageCount += 1
                If PageCount >= listbox1.SelectedItems.Count Then
                    e.HasMorePages = False
                    PageCount = 0 'add this line to set PageCount back to 0
                Else
                    e.HasMorePages = True
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
          
        End Sub
    This is thanks to Mr. tommytwotrain and Mr. IronRazerz for Help me and My thanks and gratitude to you


    Yes well you have a simple print routine so you dont get errors in it but in a more complex situation you can get unexpected errors in the print routine and the execution will jump out of the print routine without resetting the counter.

    So if you have a multipage doc and only set the counter in the print routine you will not be able to print again after an error. Edit: in some cases.

    That is all I am saying.



    • Edited by tommytwotrain Saturday, June 3, 2017 3:54 PM
    • Marked as answer by srajmuneer Saturday, June 3, 2017 6:16 PM
    Saturday, June 3, 2017 3:51 PM