Question Can't change textbox text from an event

PabloMDiez

New member
Joined
Jan 28, 2010
Messages
3
Programming Experience
3-5
Hi there!
I'm trying to solve a problem with my project.
I got a Sub which processes a code, and then it does whatever the code said.
Example.
Code = "Black" -> Turns screen black.
Code = "OFF" -> Turns off the PC.
And so on.
If I call that Sub from Immediate console, It works perfectly.
But if that Sub is called from an event, It does nothing, and usually throws an Exception.
I read somewhere that I can fix this by using Threads, but I don't understand how that can help and make it work.

Could you help me?

If needed, I can post an outline example of the code.

PS: Excuse my english :)
 
Sorry. I solved that textbox problem by using a weird Invoke thing
The whole code is correct, but doesn't work since every control property that has to be changed throws the Cross Thread Exception.
Is there any way to make it work without making new Subs and Invoke things?

Sorry if I can't explain myself very fine, my VS.NET is in Spanish.
 
Is there any way to make it work without making new Subs and Invoke things?
We would have to see what you have before we could make suggestions on how to improve it.
 
Sorry I was out.

For example:
VB.NET:
Select Case Code
  Case "Example"
    TextBox1.Text = "Example!"
  Case "Other Form"
    frmOtherForm.TextBox1.Text = "Example 2!"
  Case "MakeVisible"
    frmOtherForm.Panel1.Visible = True
End Select

Ok, that sub, for example, will throw lots of those CrossThread exceptions if called from an event.
So I figured out how to change textbox variables, by a sub.

VB.NET:
Public Delegate Sub ChangeTextBoxInvoker(ByVal TextBoxControl as Control, ByVal text as String)

Public Sub ChangeTextBox(ByVal TextBoxControl as Control, ByVal text as String)
  With TextBoxControl
    If .InvokeRequired Then
      .Invoke(New ChangeTextBoxInvoker(AddressOf ChangeTextBox), TextBoxControl, text)
    Else
      If TypeOf control Is TextBox Then
        .Text = Valor
      End If
    End If
  End With
End Sub

I just can't understand why I do have to do that.. In VB6 it was as simple as TextBox1 = "Blah", and not a whole sub, and coding mistakes :(
And I have lots of instructions with that "Code" variable. It's SO unpracticall to do a Sub for each one/code/control. And I don't think making a general "InvokerSub" will fix everything in a optimized and good way...

Can you help me?
 
That first code, if that is in a Sub you can invoke (call) that method on UI thread and all is ok.
VB.NET:
Sub Method
Select Case code...
From your secondary thread:
VB.NET:
Me.Invoke(New MethodInvoker(AddressOf Method))
"Me" refers to the form instance, I saw you referenced Textbox1 directly so you must be making this call from a Form class. "Me" could be substituted by any control instance belonging to UI thread really.
 
Back
Top