Cross-thread operation not valid: Control 'Form2' accessed from a thread other than the thread it wa

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hye recently i have encountered the error Cross-thread operation not valid: Control Form2 accessed from a thread other than the thread it was created on." i have developed a support tool to insert new record inside from excel to sql sever database table. So i create a another form which form 2 which act as loading included loading gif image. The form 2 will call by thread when invoked and open as modal dialog. The problem how i can close the modal dialog if the thread in nothing or the insert process finished.Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With OpenFileDialog1
.Title = "Excel File to Edit" DIALOG BOX TITLE.
.FileName = ""
.Filter = "Excel File|*.xlsx;*.xls" FILTER ONLY EXCEL FILES IN FILE TYPE.

Dim sFileName As String = ""
Dim sSheetName = "Sheet1"
If .ShowDialog() = DialogResult.OK Then
sFileName = .FileName()
End If
If Trim(sFileName) <> "" Then
Call ShowLoading()
ExcelLoop(sFileName)
Dim ds As DataSet = ReadSheet(sFileName, sSheetName)
ImportIntoDatabase(ds)
If th IsNot Nothing Then
th.Abort()
objFrm2.Close()
End If
Me.Close()
End If
End With
End Sub
Private Sub ShowLoading()

If Me.InvokeRequired Then
objFrm2.ShowDialog()

Else
Start the thread that will execute this method

th = New Threading.Thread(AddressOf ShowLoading)
th.IsBackground = True
th.Start()

End If

End Sub
The error pop out at objForm2.Close() command. Hope anyone can help me to clear this problem.

View the full article
 
Back
Top