I am trying my best to figure out how to go about this error i am reciving:
Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on.
I have a backgroundworker thats extracting cells from an excel worksheet and placing them into the listview.
Upon form load i do this:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call createListView()
End Sub
Private Sub createListView()
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True
ListView1.HideSelection = False
ListView1.MultiSelect = False
ListView1.Columns.Add("Column Name", 150)
ListView1.Columns.Add("Column Number", 150)
End Sub
Then i call the backgroundworker after the user selects a file:
If openFileDialog1.ShowDialog() = DialogResult.OK Then
stFilePathAndName = openFileDialog1.FileName
ProgressBar1.Style = ProgressBarStyle.Marquee
BGWxml2excel = New System.ComponentModel.BackgroundWorker
BGWxml2excel.WorkerReportsProgress = True
BGWxml2excel.WorkerSupportsCancellation = True
BGWxml2excel.RunWorkerAsync()
End If
Then i process with getting the excel column count and values so that i can populate the listview with it:
Private Sub BGWxml2excel_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BGWxml2excel.DoWork
Call xml2Excel(stFilePathAndName)
End Sub
Private Sub xml2Excel(ByRef theDirOfFile As String)
Dim xlsApp As Excel.Application
Dim xlsWB As Excel.Workbook
Dim xlsSheet As Excel.Worksheet
Dim columnCount As Integer = 0
xlsApp = New Excel.Application
xlsApp.Visible = False
xlsApp.DisplayAlerts = False
xlsWB = xlsApp.Workbooks.OpenXML(Filename:=theDirOfFile, LoadOption:=XlXmlLoadOption.xlXmlLoadImportToList)
xlsSheet = xlsWB.Worksheets(1)
xlsSheet.Select()
columnCount = xlsSheet.UsedRange.Columns.Count
Dim lvi As New ListViewItem
Dim x As Integer = 1
Do Until x = columnCount + 1
lvi.Text = xlsSheet.Cells(1, x).value
lvi.SubItems.Add(x)
ListView1.Items.Add(lvi)
x = x + 1
Loop
'xlsSheet.SaveAs("c:\_tempExcelFile.xlsx", FileFormat:=51, CreateBackup:=False)
xlsWB.Close()
xlsApp.Quit()
End Sub
The error is on this line:
ListView1.Items.Add(lvi)
What can i do in order to correct this odd proglem?
Thanks!
David