none
I get problem in backgroundWorker1_DoWork

    Question

  • I get this problem when I press on the Convert Button:

    {System.InvalidOperationException was unhandled by user code
    Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on.}

    The Source Code:

        Dim TempFolder As String
    
    Dim
    ImageName As String


    Private
    Sub Convert_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Convert_Button.Click
    TempFolder = Environment.GetEnvironmentVariable("TEMP") & "\PNG_Conver\" BackgroundWorker1.RunWorkerAsync()
    End
    Sub

    Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork For c As Integer = Nothing To ListView1.CheckedItems.Count Throw1: If c = ListView1.CheckedItems.Count Then Exit Sub End If

    Try
    If ListView1.CheckedItems.Item(c).SubItems(2).Text = "Error" Then
    c += 1 End If ImageName = "PNG_" & c & ".png" My.Computer.FileSystem.CopyFile(ListView1.CheckedItems.Item(c).SubItems(1).Text, TempFolder & ImageName, True)
    BackgroundWorker1.ReportProgress(c) ListView.CheckedItems.Item(c).SubItems(2).Text = "Completed" Catch ex As Exception ListView1.CheckedItems.Item(c).SubItems(2).Text = "Error" ListView1.CheckedItems.Item(c).BackColor = Color.LightCoral ErrorDialog.Error_ListBox.Items.Add(ListView1.CheckedItems.Item(c).Text)
    c += 1 GoTo Throw1 End Try Next End Sub
    Please Help...
    Tuesday, February 16, 2010 4:53 PM

Answers

  • Rudedog2, I'm done it ... thanks

    Thanks for every one...

    This the end Source Code:

        Dim TempFolder As String = String.Empty
        Dim appName As String = My.Application.Info.AssemblyName
    
        Private Sub Convert_Button_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Convert_Button.Click
            TempFolder = Environment.GetEnvironmentVariable("TEMP") & "\PNG_Conver\"
            Convert_Button.Enabled = False
            ProgressBar1.Maximum = ListView1.CheckedItems.Count
    
            Dim CheckedItems As New List(Of ListViewItem)
            For Each checkedItem As ListViewItem In ListView1.CheckedItems
                CheckedItems.Add(checkedItem)
            Next
            BackgroundWorker1.RunWorkerAsync(CheckedItems)
        End Sub
    
        Private Sub backgroundWorker1_DoWork(ByVal sender As Object, _
        ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim ImageName As String = String.Empty  'declare and assign a default value
            Dim currentItem As Integer = -1
            '
            ' access argument data
            '
            Dim CheckedItems As List(Of ListViewItem) = CType(e.Argument, List(Of ListViewItem))
            '
            ' process list of checked items
            '
            For Each item As ListViewItem In CheckedItems
                If currentItem = CheckedItems.Count Then
                    Exit Sub
                End If
                If Not e.Cancel Then
                    Try
                        currentItem += 1
                        ImageName = "PNG_" & currentItem.ToString() & ".png"
                        My.Computer.FileSystem.CopyFile(CheckedItems.Item(currentItem).SubItems(1).Text, _
                                                        TempFolder & ImageName, True)
                        BackgroundWorker1.ReportProgress(currentItem, "Completed")
                    Catch ex As Exception
                        BackgroundWorker1.ReportProgress(currentItem, "Error")
                        e.Cancel = True
                        Throw ex
                    End Try
                End If
            Next
        End Sub
    
        Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object, _
        ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
        Handles BackgroundWorker1.ProgressChanged
            ProgressBar1.Value = e.ProgressPercentage
    
            Dim currentItem As Integer = e.ProgressPercentage
            Dim currentText As String = CType(e.UserState, String)
    
            ListView1.CheckedItems.Item(currentItem).SubItems(2).Text = currentText
            If currentText = "Completed" Then
                ListView1.CheckedItems.Item(currentItem).BackColor = Color.LightGreen
            End If
            If currentText = "Error" Then
                ListView1.CheckedItems.Item(currentItem).BackColor = Color.Salmon
                ErrorDialog.Error_ListBox.Items.Add(ListView1.CheckedItems.Item(currentItem).Text)
            End If
        End Sub
    
        Private Sub backgroundWorker1_Completed(ByVal sender As System.Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
        Handles BackgroundWorker1.RunWorkerCompleted
            Convert_Button.Enabled = True
            ProgressBar1.Value = 0
            Convert_Button.Text = "Convert"
    
            If ErrorDialog.Error_ListBox.Items.Count > 0 Then
                ErrorDialog.ShowDialog()
            End If
        End Sub
    
        Private Sub Add_Button_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Add_Button.Click
            Try
                If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim file As String
                    For Each file In OpenFileDialog1.FileNames
                        Dim NewItem As New ListViewItem
                        Convert_Button.Enabled = True
                        Name = Path.GetFileName(file)
                        NewItem.Text = Name
                        NewItem.SubItems.Add(file)
                        NewItem.SubItems.Add("-")
                        NewItem.Checked = True
                        ListView1.Items.Add(NewItem)
                    Next file
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message, appName, MessageBoxButtons.OK, _
                                MessageBoxIcon.Asterisk)
            End Try
        End Sub
    • Marked as answer by Motaz Alnuweiri Wednesday, February 17, 2010 9:04 PM
    • Edited by Motaz Alnuweiri Friday, February 19, 2010 8:56 PM Correcting some mistakes
    Wednesday, February 17, 2010 8:53 PM

All replies

  • Use ReportProgress.  The BackgroundWorker is specifically constructed to allow you to access the UI thread.  You're misusing it badly.
    Tuesday, February 16, 2010 5:52 PM
  • Use ReportProgress.  The BackgroundWorker is specifically constructed to allow you to access the UI thread.  You're misusing it badly.

    Thank you but...
    I don't understand what do you mean ... please explain.
    Tuesday, February 16, 2010 6:47 PM
  • You can't access your ListView directly from the BackgroundWorker thread.  Use the UserState object of ReportProgress to return info to the UI thread where you can safely access  the  ListView.
    Tuesday, February 16, 2010 7:03 PM
  • The BackgroundWorker does it's work on a separate thread from the User Interface (you're user controls). To prevent problems you can't change things in one thread from another thread. The ReportProgress code executes in the UI thread so it can modify the UI.


    Bill Gates look out!
    Tuesday, February 16, 2010 7:04 PM
  • Take a look at this thread so that you will understand johnwein suggestion

    Cross-thread operation not valid



    kaymaf
    If that what you want, take it. If not, ignored it and no complain

    CODE CONVERTER SITE : http://www.carlosag.net/Tools/CodeTranslator/.

    Tuesday, February 16, 2010 7:39 PM
  • As a general rule, BGW threads should not access variables declared and instantiated on the UI thread,
    I re-wrote you code.  Test it out in a new test form.  I could not test it.  I don't have your List of Items.

    '*****************************************************************'

    Imports System.ComponentModel

    Public Class Form_ListViewWorker

        Dim TempFolder As String

        Private Sub Convert_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Convert_Button.Click


            TempFolder = Environment.GetEnvironmentVariable("TEMP") & "\PNG_Conver\"
            BackgroundWorker1.RunWorkerAsync(ListView1.CheckedItems)
        End Sub


        Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim ImageName As String = String.Empty  'declare and assign a default value
            Dim currentItem As Integer = -1
            '
            ' access argument data
            '
            Dim CheckedItems As ListView.CheckedListViewItemCollection = CType(e.Argument, ListView.CheckedListViewItemCollection)
            '
            ' process list of checked items
            '
            For Each item As ListViewItem In CheckedItems
                If Not e.Cancel Then
                    If item.SubItems(2).Text = "Error" Then
                        currentItem += 1
                        Try
                            ImageName = "PNG_" & currentItem.ToString() & ".png"
                            My.Computer.FileSystem.CopyFile(CheckedItems.Item(currentItem).SubItems(1).Text, TempFolder & ImageName, True)
                            BackgroundWorker1.ReportProgress(currentItem, "Completed")
                        Catch ex As Exception
                            BackgroundWorker1.ReportProgress(currentItem, "Error")
                            e.Cancel = True
                            Throw ex
                        End Try
                    End If
                End If
            Next

        End Sub

        Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
            Dim currentItem As Integer = e.ProgressPercentage
            Dim currentText As String = CType(e.UserState, String)
            ListView1.CheckedItems.Item(currentItem).SubItems(2).Text = currentText
            If currentText = "Completed" Then
                ListView1.CheckedItems.Item(currentItem).BackColor = Color.LightGreen
            End If
            If currentText = "Error" Then
                ListView1.CheckedItems.Item(currentItem).BackColor = Color.LightBlue
            End If
        End Sub

        Private Sub backgroundWorker1_Completed(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
            If e.Error IsNot Nothing Then
                ' an exception occured
                MessageBox.Show("background exception")
            End If
            If e.Cancelled = True Then
                ' worker operation was cancelled
                MessageBox.Show("background error")
            End If

        End Sub
    End Class


    '*****************************************************************'


    You should catch exceptions thrown by the worker in the Completed event handler.
    If you catch any errors in your DoWork event handler, you should re-throw them.
    Depending upon how you re-throw them, catching those exceptions can get complicated.

    Hope this helps.

    Rudy  =8^D

    Mark the best replies as answers. "Fooling computers since 1971."
    • Edited by Rudedog2MVP Tuesday, February 16, 2010 8:01 PM : Checked Collection
    Tuesday, February 16, 2010 7:59 PM
  • Thanks for every one...

    Rudedog2 thank you but it show the same error...

    {System.InvalidOperationException was unhandled by user code
    Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on.}
    Tuesday, February 16, 2010 8:12 PM
  • On what line?  I do not get any errors with an empty list.

    Did you first test it out on a new form? 


    Mark the best replies as answers. "Fooling computers since 1971."
    • Edited by Rudedog2MVP Tuesday, February 16, 2010 8:21 PM
    Tuesday, February 16, 2010 8:16 PM
  • On what line?  I do not get any errors with an empty list.

    Mark the best replies as answers. "Fooling computers since 1971."

    Hi... Rudedog2 it's in this line:

    (For Each item As ListViewItem In CheckedItems) -> {System.InvalidOperationException was unhandled by user code
    Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on.}
    Tuesday, February 16, 2010 8:21 PM
  • You can't do that Rudy.  You're passing the ListView to the worker thread.  Make a copy of the items.
    Tuesday, February 16, 2010 8:31 PM
  • You can't do that Rudy.  You're passing the ListView to the worker thread.  Make a copy of the items.


    Yeah, yeah, yeah.  This works.  List(Of ListViewItem).
    Technically, I didn't make a copy.



        Private Sub Convert_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Convert_Button.Click
            TempFolder = Environment.GetEnvironmentVariable("TEMP") & "\PNG_Conver\"
            Dim CheckedItems As List(Of ListViewItem) = New List(Of ListViewItem)
            For Each checkedItem As ListViewItem In ListView1.CheckedItems
                CheckedItems.Add(checkedItem)
            Next
            BackgroundWorker1.RunWorkerAsync(CheckedItems)
        End Sub


        Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim ImageName As String = String.Empty  'declare and assign a default value
            Dim currentItem As Integer = -1
            '
            ' access argument data
            '
            Dim CheckedItems As List(Of ListViewItem) = CType(e.Argument, List(Of ListViewItem))
            '
            ' process list of checked items
            '
            For Each item As ListViewItem In CheckedItems
                If Not e.Cancel Then
                    currentItem += 1
                    If item.SubItems(2).Text = "Error" Then
                        Try
                            ImageName = "PNG_" & currentItem.ToString() & ".png"
                            'My.Computer.FileSystem.CopyFile(CheckedItems.Item(currentItem).SubItems(1).Text, TempFolder & ImageName, True)
                            BackgroundWorker1.ReportProgress(currentItem, "Completed")
                        Catch ex As Exception
                            BackgroundWorker1.ReportProgress(currentItem, "Error")
                            e.Cancel = True
                            Throw ex
                        End Try
                    End If
                End If
            Next
        End Sub


    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, February 16, 2010 8:35 PM
  • That throws an exception, too. 


    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, February 16, 2010 8:41 PM
  • It's work but the images not copy...
    Tuesday, February 16, 2010 8:51 PM
  • You're still referencing the ListView.  New List, New Item.
    Tuesday, February 16, 2010 8:53 PM
  • That throws an exception, too. 


    Mark the best replies as answers. "Fooling computers since 1971."


    Now I've made a copy.
    I still have no good way to test it out.


        Private Sub Convert_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Convert_Button.Click
            TempFolder = Environment.GetEnvironmentVariable("TEMP") & "\PNG_Conver\"
            Dim CheckedItems As List(Of ListViewItem) = New List(Of ListViewItem)
            For Each checkedItem As ListViewItem In ListView1.CheckedItems
                Dim item As ListViewItem = New ListViewItem(checkedItem.Text)
                For Each subItem As ListViewItem.ListViewSubItem In checkedItem.SubItems
                    Dim sItem As ListViewItem.ListViewSubItem = New ListViewItem.ListViewSubItem(item, subItem.Text)
                    item.SubItems.Add(sItem)
                Next
                CheckedItems.Add(item)
            Next
            BackgroundWorker1.RunWorkerAsync(CheckedItems)
        End Sub


    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, February 16, 2010 8:56 PM
  • You're still referencing the ListView.  New List, New Item.


    Yeah.  Technically, I wasn't making a copy.  I knew that.
    But initially, it appeared to work. 
    A closer look showed that it was still throwing the "Cross Thread Exception".

    EDIT:  I always have a monster of a time Debugging in VB.  Man!


    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, February 16, 2010 9:02 PM
  • (I still have no good way to test it out.)....


    Make a ListView and add this Columns (Name , Location , Status)

    Name = the name of the image.
    location = the path of the image.
    Status = the status of the converting (Complete or Error)

    Add Items (this the example) >

        Private Sub AddFilesButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFilesButton.Click
            Try
                If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim file As String = String.Empty
                    Dim name As String = String.Empty
                    
                     For Each file In OpenFileDialog1.FileNames
                        Dim NewItem As New ListViewItem
                        CheckBox1.Enabled = True
                        CheckBox1.Checked = True
                        Convert_Button.Enabled = True
                        ConvertItemsToolStripMenuItem.Enabled = True
                        name = Path.GetFileName(file)
                        NewItem.Text = name
                        NewItem.SubItems.Add(file)
                        NewItem.SubItems.Add("-")
                        NewItem.Checked = True
                        ListView1.Items.Add(NewItem)
                    Next file
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message, AppName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            End Try
        End Sub
    Tuesday, February 16, 2010 9:14 PM
  • Does the above mean that the last change did not help?
    It might not write files because of this IF statement in DoWork.

    If item.SubItems(2).Text = "Error" Then


    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, February 16, 2010 9:18 PM
  • Does the above mean that the last change did not help?
    It might not write files because of this IF statement in DoWork.

    If item.SubItems(2).Text = "Error" Then


    Mark the best replies as answers. "Fooling computers since 1971."

    It's small mistake from you in (If item.SubItems(2).Text = "Error" Then)

    It Should be (If Not item.SubItems(2).Text = "Error" Then) you forget Not.

    Thank you so much... (Rudedog2)
    Tuesday, February 16, 2010 9:32 PM
  • Try this:

    Public Class Form1
        Friend WithEvents NameCol As System.Windows.Forms.ColumnHeader
        Friend WithEvents StatusCol As System.Windows.Forms.ColumnHeader
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            ' -------------------------------
            ' Add two columns to the listview
            ' -------------------------------
            Me.NameCol = New System.Windows.Forms.ColumnHeader
            Me.StatusCol = New System.Windows.Forms.ColumnHeader
            Me.NameCol.Text = "ItemName"
            Me.NameCol.Width = 118
            Me.StatusCol.Text = "ItemStatus"
            Me.StatusCol.Width = 107
            Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.NameCol, Me.StatusCol})
            ' -------------------------------
    
            For i As Int32 = 0 To 5
                ListView1.Items.Add(New ListViewItem(New String() {"Item " & i.ToString(), "tbd"}))
            Next
    
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim t As New Threading.Thread(AddressOf doWork)
            t.Start()
        End Sub
    
        Private Sub doWork()
    
            For i As Int32 = 0 To ListView1.Items.Count - 1
                ' -------------------------------
                ' Choose one of these two methods
                ' -------------------------------
                ' Invoke(New updateStatus2Sig(AddressOf updateStatus2), i, "foo")
                updateStatus(i, "done")
                ' -------------------------------
                Threading.Thread.Sleep(1 * 1000)
            Next
    
        End Sub
    
        ' -------------------------------
        ' Method 1
        ' -------------------------------
        Delegate Sub updateStatusSig(Of t1, t2)(ByVal i As Int32, ByVal status As String)
        Private Sub updateStatus(ByVal i As Int32, ByVal status As String)
            If InvokeRequired Then
                Dim del As updateStatusSig(Of Int32, String) = AddressOf updateStatus
                Invoke(del, i, status)
                Exit Sub
            End If
            ListView1.Items(i).SubItems(1).Text = status
        End Sub
        ' -------------------------------
    
        ' -------------------------------
        ' Method 2
        ' -------------------------------
        Public Delegate Sub updateStatus2Sig(ByVal i As Int32, ByVal message As String)
        Public Sub updateStatus2(ByVal i As Int32, ByVal message As String)
            ListView1.Items(i).SubItems(1).Text = message
        End Sub
        ' -------------------------------
    
    End Class
    


    jon.stromer.galley
    Tuesday, February 16, 2010 10:57 PM
  • Thank you jgalley...

    Rudedog2 this question for you...

    How to add CombBox1 to backgroundWorker1_DoWork like the ListView1?


    Tuesday, February 16, 2010 11:24 PM
  • Rudedog2 this question for you...

    How to add CombBox1 to backgroundWorker1_DoWork like the ListView1?


    And I thought the whole point of this thead was getting ListView1 out of the DoWork!
    Tuesday, February 16, 2010 11:37 PM
  • oops,

    I thought the point was how to update Listview1 from within doWork.

    What is the point then?

    jon.stromer.galley
    Wednesday, February 17, 2010 12:43 AM
  • Thank you jgalley...

    Rudedog2 this question for you...

    How to add CombBox1 to backgroundWorker1_DoWork like the ListView1?




    Don't add it. 
    Handle it with a another worker instance.

    Mark the best replies as answers. "Fooling computers since 1971."
    Wednesday, February 17, 2010 1:43 PM
  • Rudedog2, I'm done it ... thanks

    Thanks for every one...

    This the end Source Code:

        Dim TempFolder As String = String.Empty
        Dim appName As String = My.Application.Info.AssemblyName
    
        Private Sub Convert_Button_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Convert_Button.Click
            TempFolder = Environment.GetEnvironmentVariable("TEMP") & "\PNG_Conver\"
            Convert_Button.Enabled = False
            ProgressBar1.Maximum = ListView1.CheckedItems.Count
    
            Dim CheckedItems As New List(Of ListViewItem)
            For Each checkedItem As ListViewItem In ListView1.CheckedItems
                CheckedItems.Add(checkedItem)
            Next
            BackgroundWorker1.RunWorkerAsync(CheckedItems)
        End Sub
    
        Private Sub backgroundWorker1_DoWork(ByVal sender As Object, _
        ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim ImageName As String = String.Empty  'declare and assign a default value
            Dim currentItem As Integer = -1
            '
            ' access argument data
            '
            Dim CheckedItems As List(Of ListViewItem) = CType(e.Argument, List(Of ListViewItem))
            '
            ' process list of checked items
            '
            For Each item As ListViewItem In CheckedItems
                If currentItem = CheckedItems.Count Then
                    Exit Sub
                End If
                If Not e.Cancel Then
                    Try
                        currentItem += 1
                        ImageName = "PNG_" & currentItem.ToString() & ".png"
                        My.Computer.FileSystem.CopyFile(CheckedItems.Item(currentItem).SubItems(1).Text, _
                                                        TempFolder & ImageName, True)
                        BackgroundWorker1.ReportProgress(currentItem, "Completed")
                    Catch ex As Exception
                        BackgroundWorker1.ReportProgress(currentItem, "Error")
                        e.Cancel = True
                        Throw ex
                    End Try
                End If
            Next
        End Sub
    
        Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object, _
        ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
        Handles BackgroundWorker1.ProgressChanged
            ProgressBar1.Value = e.ProgressPercentage
    
            Dim currentItem As Integer = e.ProgressPercentage
            Dim currentText As String = CType(e.UserState, String)
    
            ListView1.CheckedItems.Item(currentItem).SubItems(2).Text = currentText
            If currentText = "Completed" Then
                ListView1.CheckedItems.Item(currentItem).BackColor = Color.LightGreen
            End If
            If currentText = "Error" Then
                ListView1.CheckedItems.Item(currentItem).BackColor = Color.Salmon
                ErrorDialog.Error_ListBox.Items.Add(ListView1.CheckedItems.Item(currentItem).Text)
            End If
        End Sub
    
        Private Sub backgroundWorker1_Completed(ByVal sender As System.Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
        Handles BackgroundWorker1.RunWorkerCompleted
            Convert_Button.Enabled = True
            ProgressBar1.Value = 0
            Convert_Button.Text = "Convert"
    
            If ErrorDialog.Error_ListBox.Items.Count > 0 Then
                ErrorDialog.ShowDialog()
            End If
        End Sub
    
        Private Sub Add_Button_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Add_Button.Click
            Try
                If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim file As String
                    For Each file In OpenFileDialog1.FileNames
                        Dim NewItem As New ListViewItem
                        Convert_Button.Enabled = True
                        Name = Path.GetFileName(file)
                        NewItem.Text = Name
                        NewItem.SubItems.Add(file)
                        NewItem.SubItems.Add("-")
                        NewItem.Checked = True
                        ListView1.Items.Add(NewItem)
                    Next file
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message, appName, MessageBoxButtons.OK, _
                                MessageBoxIcon.Asterisk)
            End Try
        End Sub
    • Marked as answer by Motaz Alnuweiri Wednesday, February 17, 2010 9:04 PM
    • Edited by Motaz Alnuweiri Friday, February 19, 2010 8:56 PM Correcting some mistakes
    Wednesday, February 17, 2010 8:53 PM
  • Your last code shouldn't work.  You shouldn't be able to access UI controls from a thread other than the UI thread as you are doing. 
    Wednesday, February 17, 2010 9:13 PM
  • John is right, you know.

    I posted code above that made a copy of the collection contents to pass to the BGW.
    What you posted is still using the code I posted, which John had noted as flawed.
    Mark the best replies as answers. "Fooling computers since 1971."


    EDIT:  This is what I posted above to make a copy of the CheckedItems collection.


        Private Sub Convert_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Convert_Button.Click
            TempFolder = Environment.GetEnvironmentVariable("TEMP") & "\PNG_Conver\"
            Dim CheckedItems As List(Of ListViewItem) = New List(Of ListViewItem)
            For Each checkedItem As ListViewItem In ListView1.CheckedItems
                Dim item As ListViewItem = New ListViewItem(checkedItem.Text)
                For Each subItem As ListViewItem.ListViewSubItem In checkedItem.SubItems
                    Dim sItem As ListViewItem.ListViewSubItem = New ListViewItem.ListViewSubItem(item, subItem.Text)
                    item.SubItems.Add(sItem)
                Next
                CheckedItems.Add(item)
            Next
            BackgroundWorker1.RunWorkerAsync(CheckedItems)
        End Sub
    • Edited by Rudedog2MVP Wednesday, February 17, 2010 9:18 PM : added code snippet
    Wednesday, February 17, 2010 9:16 PM
  • Why?...why?...why?...I tested it and it work.

    I add two images to ListView1 and clicked to Convert Button then I gone to Temp directory
    I found the PNG_Convertor folder and the two images with name (PNG_0.png and PNG_1.png).

    Where the problem ?
    Friday, February 19, 2010 9:07 PM
  • Why?...why?...why?...I tested it and it work.

    I add two images to ListView1 and clicked to Convert Button then I gone to Temp directory
    I found the PNG_Convertor folder and the two images with name (PNG_0.png and PNG_1.png).

    Where the problem ?

    {System.InvalidOperationException was unhandled by user code
    Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on.}

    Set CheckForIllegalCrossThreadCalls = False and you can be sure your program won't crash until it's deployed.
    Friday, February 19, 2010 9:42 PM