[RESOLVED] Cross-thread operation not valid
In response to a "Cross-thread operation not valid: Control 'RecordAddedTextBox' accessed from a thread other than the one it was created on." error I have added a routine obtained from Microsoft Help and that is giving me a compile error.
This is my original code:
Code:
Private Sub foo(ByVal tbx As Object)
'when this code was in the Enter event handler the cursor was
'not visible until the sounds played.
Dim tb As TextBox = DirectCast(tbx, TextBox)
Select Case tbx.name
Case "NameTextBox"
speaker.Speak("Name")
Case "RecordAddedDateTextBox"
Me.RecordAddedDateTextBox.Text = Now() <-- ERROR HERE
Case "ConversationTextBox"
speaker.Speak("Conversation")
End Select
Threading.Thread.Sleep(250)
End Sub
And this is the code which I added:
Code:
Private Sub SetText(ByVal [text] As String)
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If Me.RecordAddedDateTextBox.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.RecordAddedDateTextBox.Text = [text]
End If
End Sub
presumably to be called from my subroutine. But SetTextCallback comes up as undefined. Since this is a strange to me I don't know how to fix it. I was hoping someone could help me and save my hours of trial and error. Is there a better way?
Of course there is more code involved which calls the subroutine with the error and I can post that if needed.
Re: Cross-thread operation not valid
You forgot to declare a delegate SetTextCallback
vb Code:
Private Delegate Sub SetTextCallback(ByVal text As String)
Private Sub foo(ByVal tbx As Object)
'when this code was in the Enter event handler the cursor was
'not visible until the sounds played.
Dim tb As TextBox = DirectCast(tbx, TextBox)
Select Case tbx.name
Case "NameTextBox"
speaker.Speak("Name")
Case "RecordAddedDateTextBox"
Me.SetText(Now.ToString())
Case "ConversationTextBox"
speaker.Speak("Conversation")
End Select
Threading.Thread.Sleep(250)
End Sub
Private Sub SetText(ByVal [text] As String)
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If Me.RecordAddedDateTextBox.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.RecordAddedDateTextBox.Text = [text]
End If
End Sub
Re: Cross-thread operation not valid